Python3 file.seek()方法

seek() 方法设置 offset 为文件的当前偏移位置。在这里参数是可选的,默认为0,这意味着绝对的文件定位,另外的一个值是1,这意味着寻求相对于当前位置,而值为2是设置寻找相对于文件的结束。

此方没有返回值。请注意,如果文件被打开使用的是'a'或'A+'追加,任何seek()操作将在下次写时撤消。

如果该文件只打开使用 'A' 追加模式写入,这种方法本质上是一个无操作,但是读取启用(模式'A+'),它在追加模式打开的文件非常有用。

如果文件在文本模式下使用“t”,只有 tell() 返回偏移开是合法的。其他偏移时会导致不确定的行为。

请注意,并非所有的文件对象都是可搜索。

语法

以下是 seek()方法的语法 -
fileObject.seek(offset[, whence])

参数

  • offset -- 这是在文件内的读/写指针的位置。

  • whence -- 这是可选的,默认为0表示绝对的文件定位;值是1时这意味着寻找相对于当前位置;以及值是2时寻找相对于文件的末尾。

返回值

此方法不返回任何值。

示例

下面的示例显示seek()方法的使用。
Assuming that 'foo.txt' file contains following text:
This is 1st line
This is 2nd line
This is 3rd line
This is 4th line
This is 5th line
#!/usr/bin/python3

# Open a file
fo = open("foo.txt", "rw+")
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

上一篇: Python3模块 下一篇: Python3文件方法