我刚接触Python(2.6),现在遇到这样的情况:我需要取消刚读取文件中的一行。以下是我大致的操作:
for line in file:
print line
file.seek(-len(line),1)
zz = file.readline()
print zz
然而,我注意到“zz”和“line”不同。我错在哪里了?谢谢。
我刚接触Python(2.6),现在遇到这样的情况:我需要取消刚读取文件中的一行。以下是我大致的操作:
for line in file:
print line
file.seek(-len(line),1)
zz = file.readline()
print zz
我认为循环读取文件和使用 seek
并不搭配。你可以尝试使用如下代码:
while True:
line = file.readline()
print line
file.seek(-len(line),1)
zz = file.readline()
print zz
# Make sure this loop ends somehow
.readline()
在文件结束时返回空字符串''
,因此退出条件为if not line: break
。 - jfs您不能将迭代器和seek()
方法混合使用。您应该选择一种方法并坚持使用。
.seek()
操作结合使用:for i, line in enumerate(iter(f.readline, ''), 1):
print i, line,
if i == 2: # read 2nd line two times
f.seek(-len(line), os.SEEK_CUR)
a
b
c
1 a
2 b
3 b
4 c
未经测试。基本上,您需要维护一个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.