Python file methodSeek()将文件的当前位置设置为偏移量。WHERCE参数是可选的,默认值为0,表示绝对文件定位,其他值为1,表示相对于当前位置的查找,2表示相对于文件结尾的查找。
没有返回值。请注意,如果使用‘a'或‘a+'打开文件进行追加,则任何Seek()操作都将在下一次写入时撤消。
如果仅使用‘a'在追加模式下打开文件以进行写入,则此方法本质上是一种无操作,但对于在启用了读取的追加模式下打开的文件(模式‘a+'),它仍然很有用。
如果使用‘t'以文本模式打开文件,则只有Tell()返回的偏移量是合法的。使用其他偏移会导致未定义的行为。
请注意,并非所有文件对象都是可查找的。
链接:https://www.learnfk.comhttps://www.learnfk.com/python/file-seek.html
来源:LearnFk无涯教程网
fileObject.seek(offset[, whence])
offset - 这是文件中读/写指针的位置。
whence - 这是可选的,默认值为0,表示绝对文件定位,其他值为1,表示相对于当前位置的查找,2表示相对于文件结尾的查找。
以下示例显示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.
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)