我正在使用file.readline()寻找特殊行的python文件指针浏览文本文件的Python文件指针。一旦找到该行,我想将文件指针传递到期望文件指针处于该读取的开始的方法(不在之后)。

我如何在文件指针上基本上撤消一个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()

我不记得是否可以安全打电话 file.seek() 内部 for line in file 循环,所以我通常只写出 while 环形。可能有更多的Pythonic方法可以做到这一点。

其他提示

您记录了线路的起点 thefile.tell() 在打电话之前 readline, ,并回到这一点,如果需要的话 thefile.seek.

>>> with open('bah.txt', 'w') as f:
...   f.writelines('Hello %s\n' % i for i in range(5))
... 
>>> with open('bah.txt') as f:
...   f.readline()
...   x = f.tell()
...   f.readline()
...   f.seek(x)
...   f.readline()
... 
'Hello 0\n'
'Hello 1\n'
'Hello 1\n'
>>> 

如您所见,可以说,搜索/讲述“对”是“撤消”,可以这么说,文件指针移动由 readline. 。当然,这只能在实际可寻求的(IE,磁盘)文件上使用,而不是(例如)在构建的类似文件的对象上使用插座的makefile方法等。

如果您的方法只想迭代文件,那么您可以使用 itertools.chain 制作适当的迭代器:

import itertools

def process(it):
    for line in it:
        print line,

with open(filename,'r') as f:
    for line in f:
        if 'marker' in line:
            it=itertools.chain((line,),f)
            process(it)
            break
fin = open('myfile')
for l in fin:
    if l == 'myspecialline':
        # Move the pointer back to the beginning of this line
        fin.seek(fin.tell() - len(l))
        break
# now fin points to the start of your special line

如果您不知道最后一行,因为您没有访问它,则可以向后阅读,直到看到新线字符:

with open(logfile, 'r') as f:
    # go to EOF
    f.seek(0, os.SEEK_END)
    nlines = f.tell()
    i=0
    while True:
        f.seek(nlines-i)
        char = f.read(1)
        if char=='\n':
            break
        i+=1
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top