Python os.lseek()方法

2019-10-16 23:04:39

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

語法

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

os.lseek(fd, pos, how)

引數

  • fd - 這是檔案描述符,需要處理。
  • pos - 這是相對於給定引數檔案的位置。os.SEEK_SET0設定相對於檔案開頭的位置,os.SEEK_CUR1用來設定它相對於當前位置; os.SEEK_END2用來設定它相對於檔案的結尾。
  • how - 這是檔案中的參考點。os.SEEK_SET0表示檔案的開頭,os.SEEK_CUR1表示當前位置,os.SEEK_END2表示檔案的結尾。

定義的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!!