撤消文件 readline() 操作,使文件指针恢复到原始状态 [英] Undo a file readline() operation so file-pointer is back in original state

查看:27
本文介绍了撤消文件 readline() 操作,使文件指针恢复到原始状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 file.readline() 以只读模式浏览文本文件的 Python 文件指针以查找特殊行.一旦我找到那行,我想将文件指针传递给一个方法,该方法期望文件指针位于该 readline 的 START 处(而不是在它之后.)

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.)

我如何从本质上撤消文件指针上的一个 file.readline() 操作?

How do I essentially undo one file.readline() operation on a file pointer?

推荐答案

你必须记住位置,在 readline 之前调用 file.tell() 然后调用 file.seek() 倒带.类似的东西:

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()

我不记得在 for line in file 循环内调用 file.seek() 是否安全,所以我通常只写出 while 循环.可能有一种更加 Pythonic 的方式来做到这一点.

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.

这篇关于撤消文件 readline() 操作,使文件指针恢复到原始状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆