如何在Python中标记一行未读
我刚接触Python(2.6),现在遇到一个问题,就是我需要把刚刚从文件中读到的一行再“未读”回去。基本上我在做的事情是这样的。
for line in file:
print line
file.seek(-len(line),1)
zz = file.readline()
print zz
不过我发现“zz”和“line”并不一样。我哪里出错了呢?
谢谢。
4 个回答
2
这个还没经过测试。简单来说,你想要保持一个后进先出(LIFO)的缓存,用来存放“未读”的行。每次读取一行时,如果缓存里有东西,就先从缓存里取出来。如果缓存里没有东西,就从文件中读取新的一行。这是个粗略的思路,但应该能帮你入门。
lineCache = []
def pushLine(line):
lineCache.append(line)
def nextLine(f):
while True:
if lineCache:
yield lineCache.pop(0)
line = f.readline()
if not line:
break
yield line
return
f = open('myfile')
for line in nextLine(f):
# if we need to 'unread' the line, call pushLine on it. The next call to nextLine will
# return the that same 'unread' line.
if some_condition_that_warrants_unreading_a_line:
pushLine(line)
continue
# handle line that was read.
3
你不能这样混用迭代器和seek()
。你应该选择一种方法,然后坚持使用它。
12
我觉得 for line in file:
和 seek
这两个东西不太搭配。你可以试试下面这种写法:
while True:
line = file.readline()
print line
file.seek(-len(line),1)
zz = file.readline()
print zz
# Make sure this loop ends somehow