Я пишу скрипт Python для чтения файла, и когда я дохожу до раздела файла, окончательный способ чтения этих строк в разделе зависит от информации, которая также указана в этом разделе. Итак, я нашел здесь что я мог бы использовать что-то вроде
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()
Есть ли способ предотвратить это?