python - 撤消文件 readline() 操作,使文件指针回到原始状态

标签 python file-io readline readlines

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

我如何从根本上撤消对文件指针的一个 file.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()

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

关于python - 撤消文件 readline() 操作,使文件指针回到原始状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3505479/

相关文章:

autocomplete - gnuplot 中的历史自动完成

python - 在哪里定义 Flask 中 url_for() 使用的域?

python - PyQT 段错误(有时)

java - 尝试从文件中读取。抛出异常

file-io - 用 Common Lisp 就地替换文件中的正则表达式

java - 在 Android 中读取文件时数据丢失

bash - 在 bash readline 中,如何使增量搜索不区分大小写

python - 为什么 Numpy 矩阵乘法运算称为 "dot"?

python - 这两个代码块(如果有)的时间复杂度有什么区别,为什么?

python - 使用 python 从不同的点开始遍历文件和列表?