【发布时间】:2014-05-06 11:29:43
【问题描述】:
我正在编写一个 Python 脚本来读取文件,当我到达文件的某个部分时,读取该部分中这些行的最终方法取决于该部分中提供的信息。所以我发现here 我可以使用类似的东西
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()
然而,我当前代码的结构如下:
fh = open(filename)
# get generator function and attach None at the end to stop iteration
items = itertools.chain(((lino,line) for lino, line in enumerate(fh, start=1)), (None,))
item = True
lino, line = next(items)
# handle special section
if line.startswith['SPECIAL']:
start = fh.tell()
for i in range(specialLines):
lino, eline = next(items)
# etc. get the special data I need here
# try to set the pointer to start to reread the special section
fh.seek(start)
# then reread the special section
但是这种方法会出现以下错误:
next() 调用禁用了显示位置
有没有办法防止这种情况发生?
【问题讨论】:
标签: python python-3.x next seek tell