撤消文件 readline() 操作,使文件指针回到原始状态
我正在使用 file.readline() 以只读模式浏览文本文件的 Python 文件指针,查找特殊行。一旦我找到该行,我想将文件指针传递给一个方法,该方法期望文件指针位于该读取行的开始位置(而不是紧随其后)。
我如何基本上撤消一个 file.readline() 操作文件指针?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须通过在读取行之前调用
file.tell()
来记住位置,然后调用file.seek()
来倒回。比如:我不记得在
for line in file
循环中调用file.seek()
是否安全,所以我通常只写出> while 循环。可能有一种更Pythonic 的方法可以做到这一点。
You have to remember the position by calling
file.tell()
before the readline and then callingfile.seek()
to rewind. Something like:I can't recall if it is safe to call
file.seek()
inside of afor line in file
loop so I usually just write out thewhile
loop. There is probably a much more pythonic way of doing this.在调用 readline 之前,您可以使用 thefile.tell() 记录该行的起点,如果需要,可以使用 thefile 返回到该点.seek。
如您所见,seek/tell“对”是“撤消”的,可以说,由 readline 执行的文件指针移动。当然,这只能对实际的可查找(即磁盘)文件起作用,而不能(例如)对使用套接字的 makefile 方法构建的类文件对象等起作用。
You record the starting point of the line with
thefile.tell()
before you callreadline
, and get back to that point, if you need to, withthefile.seek
.as you see, the seek/tell "pair" is "undoing", so to speak, the file pointer movement performed by
readline
. Of course, this can only work on an actual seekable (i.e., disk) file, not (e.g.) on file-like objects built w/the makefile method of sockets, etc etc.如果您的方法只是想迭代文件,那么您可以使用 itertools.chain 来创建适当的迭代器:
If your method simply wants to iterate through the file, then you could use
itertools.chain
to make an appropriate iterator:如果您不知道最后一行,因为您没有访问过它,您可以向后阅读,直到看到换行符:
If you don't know the last line because you didn't visit it you can read backwards until you see a newline character: