Python的lseek()
方法將檔描述符fd
的當前位置設置為給定位置pos
,由how
指定如何修改。
語法
以下是lseek()
方法的語法 -
os.lseek(fd, pos, how)
參數
- fd - 這是檔描述符,需要處理。
- pos - 這是相對於給定參數檔的位置。
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()
方法的用法。
#!/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!!
上一篇:
Python os模組方法
下一篇:
Python異常處理