目录

file.seek(offset[, whence])

描述 (Description)

方法seek()设置文件在偏移处的当前位置。 whence参数是可选的,默认为0,表示绝对文件定位,其他值为1表示相对于当前位置的搜索,2表示相对于文件结束的搜索。

没有回报价值。 请注意,如果打开文件以使用“a”或“a +”进行追加,则在下次写入时将撤消任何seek()操作。

如果仅使用'a'打开文件以追加模式写入,则此方法基本上是无操作,但对于在追加模式下打开且启用读取的文件(模式'a +')仍然有用。

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

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

语法 (Syntax)

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

fileObject.seek(offset[, whence])

参数 (Parameters)

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

  • whence - 这是可选的,默认为0表示绝对文件定位,其他值为1表示相对于当前位置的搜索,2表示相对于文件结束的搜索。

返回值 (Return Value)

此方法不返回任何值。

例子 (Example)

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

Python is a great language
Python is a great language

#!/usr/bin/python
# Open a file
fo = open("foo.txt", "rw+")
print "Name of the file: ", fo.name
# Assuming file has following 5 lines
# This is 1st line
# This is 2nd line
# This is 3rd line
# This is 4th line
# This is 5th line
line = fo.readline()
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 opend file
fo.close()

当我们运行上面的程序时,它产生以下结果 -

Name of the file:  foo.txt
Read Line: Python is a great language.
Read Line: Python is a great language.
↑回到顶部↑
WIKI教程 @2018