Python的lseek()
方法將檔案描述符fd
的當前位置設定為給定位置pos
,由how
指定如何修改。
語法
以下是lseek()
方法的語法 -
os.lseek(fd, pos, how)
引數
os.SEEK_SET
或0
設定相對於檔案開頭的位置,os.SEEK_CUR
或1
用來設定它相對於當前位置; os.SEEK_END
或2
用來設定它相對於檔案的結尾。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()
方法的用法。
#!/usr/bin/python3
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!!