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异常处理