D.S*_*ley 46
您必须通过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()
Run Code Online (Sandbox Code Playgroud)
如果是安全调用我不记得file.seek()
一个内for line in file
循环,所以我通常只是写出来的while
循环.这样做可能有更多的pythonic方式.
Ale*_*lli 11
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'
>>>
Run Code Online (Sandbox Code Playgroud)
如你所见,搜索/告诉"对"是"撤消",可以说,文件指针移动由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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
42273 次 |
最近记录: |