os.lseek() 方法



描述

lseek() 方法將檔案描述符 fd 的當前位置設定為給定的位置 pos,並由 how 修改。

語法

以下是 lseek() 方法的語法:

os.lseek(fd, pos, how)

引數

  • pos − 這是相對於給定引數 how 的檔案中的位置。您可以使用 os.SEEK_SET 或 0 來設定相對於檔案開頭的相對位置,使用 os.SEEK_CUR 或 1 來設定相對於當前位置的相對位置;使用 os.SEEK_END 或 2 來設定相對於檔案結尾的相對位置。

  • how − 這是檔案中的參考點。os.SEEK_SET 或 0 表示檔案開頭,os.SEEK_CUR 或 1 表示當前位置,os.SEEK_END 或 2 表示檔案結尾。

已定義的pos 常量

  • os.SEEK_SET - 0

  • os.SEEK_CUR - 1

  • os.SEEK_END - 2

返回值

此方法不返回值。

示例

以下示例顯示了 lseek() 方法的使用。

import os, sys

# Open a file
fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT )

# Write one string
line="This is test"
b=line.encode()
os.write(fd, b)

# Now you can use fsync() method.
# Infact here you would not be able to see its effect.
os.fsync(fd)

# Now read this file from the beginning
os.lseek(fd, 0, 0)
line = os.read(fd, 100)
print ("Read String is : ", line.decode())

# Close opened file
os.close( fd )
print ("Closed the file successfully!!")

當我們執行以上程式時,它會產生以下結果:

Read String is : This is test
Closed the file successfully!!
python_os_file_directory_methods.htm
廣告