Python文件seek()方法

Python文件的seek()方法将文件的当前位置设置为偏移量(offset)。 whence参数是可选的,默认为0,表示绝对文件定位,其他值为1,这意味着相对于当前位置进行搜索,2表示相对于文件的结尾进行搜索。

seek()方法没有返回值。 请注意,如果文件使用“a”或“a+”模式打开进行附加,则在下一次写入时,任何seek()操作都将被撤销。

如果仅使用’a‘在附加模式下打开该文件,该方法基本上是无操作的,但是对于在启用读取(模式’a+‘)的附加模式下打开的文件,该方法仍然有用。

如果使用’t‘以文本模式打开文件,则只有由tell()返回的偏移是合法的。使用其他偏移会导致未定义的行为。

语法

以下是seek()方法的语法 -

fileObject.seek(offset[, whence])

参数

  • offset − 这是文件中读/写指针的位置。
  • whence − 这是可选的,默认为0,表示绝对文件定位,其他值为1,这意味着相对于当前位置进行搜索,2表示相对于文件的末尾进行搜索。

返回值

  • 此方法不返回任何值。

示例

假设’foo.txt‘文件中包含以下行 -

This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line

以下示例显示了seek()方法的用法。

#!/usr/bin/python3

# Open a file
fo = open("foo.txt", "r+")
print ("Name of the file: ", fo.name)

line = fo.readlines()
print ("Read Line: %s" % (line))

# Again set the pointer to the beginning
fo.seek(0, 0)
line = fo.readline()
print ("Read Line: %s" % (line))

# Close opened file
fo.close()

执行上面代码后,将得到以下结果 -

Name of the file:  foo.txt
Read Line: ['This is 1st line\n', 'This is 2nd line\n', 'This is 3rd line\n', 'This is 4th line\n', 'This is 5th line']
Read Line: This is 1st line

上一篇: Python文件对象方法 下一篇: Python os模块方法