Python:取消Python文件的readline()操作,使文件指针回到原始状态 [英] Python: Undo a Python file readline() operation so file pointer is back in original state
问题描述
我正在以只读模式使用file.readline()查找特定行来浏览文本文件的Python文件指针。一旦我找到那一行,我想将文件指针传递给一个期望文件指针位于readline开始处的方法(不是之后)。
如何从本质上撤销对文件指针的一个file.readline()操作?解析方法
您必须记住在readline之前调用 file.tell()
,然后调用 file.seek()
来后退。例如:
fp = open('myfile')
last_pos = fp.tell()
line = fp.readline()
while line!='':
if line =='SPECIAL':
fp.seek(last_pos)
other_function(fp)
$ break
last_pos = fp.tell()
line = fp.readline()
我不记得在中的
file.seek()
用于文件$ c中的行是否安全$ c>循环,所以我通常只写出而
循环。这可能是一个更pythonic这样做的方式。
I'm browsing through a Python file pointer of a text file in read-only mode using file.readline() looking for a special line. Once I find that line I want to pass the file pointer to a method that is expecting the file pointer to be at the START of that readline (not right after it.)
How do I essentially undo one file.readline() operation on a file pointer?
You have to remember the position by calling file.tell()
before the readline and then calling file.seek()
to rewind. Something like:
fp = open('myfile')
last_pos = fp.tell()
line = fp.readline()
while line != '':
if line == 'SPECIAL':
fp.seek(last_pos)
other_function(fp)
break
last_pos = fp.tell()
line = fp.readline()
I can't recall if it is safe to call file.seek()
inside of a for line in file
loop so I usually just write out the while
loop. There is probably a much more pythonic way of doing this.
这篇关于Python:取消Python文件的readline()操作,使文件指针回到原始状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!