Python3 os.lseek()方法

lseek()方法设置文件描述符fd的当前位置为给定的位置pos,由 how 修改

语法

下面是 lseek()方法的语法:
os.lseek(fd, pos, how)

参数

  • fd -- 这是需要进行处理的文件描述符

  • 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()方法的使用。
#!/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!!

上一篇: Python3文件方法 下一篇: Python3 os文件目录的方法