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

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

问题描述

我正在使用file.readline()以只读模式浏览文本文件的Python文件指针,以查找特殊行.找到该行后,我想将文件指针传递给一个方法,该方法期望文件指针位于该读取行的开始位置(而不是紧随其后.)

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?

推荐答案

您必须记住位置,方法是在阅读行之前调用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循环.可能有更多的Python方式可以做到这一点.

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天全站免登陆