我正在使用 file.readline() 以只读模式浏览文本文件的 Python 文件指针,以查找特殊行。一旦找到该行,我想将文件指针传递给一个方法,该方法期望文件指针位于该 readline 的 START 处(而不是紧随其后。)
我如何从本质上撤消对文件指针的一个 file.readline() 操作?
file.tell()
您必须通过在 readline 之前调用然后调用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
循环。可能有一种更蟒蛇的方式来做到这一点。
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
. 当然,这只能在实际的可查找(即磁盘)文件上工作,而不是(例如)在使用套接字的 makefile 方法等构建的类文件对象上工作。
如果您的方法只是想遍历文件,那么您可以使用itertools.chain
来制作适当的迭代器:
import itertools
# do something to the marker line and everything after
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