Python:为什么readline()函数不';不适合文件循环
我有以下代码:Python:为什么readline()函数不';不适合文件循环,python,Python,我有以下代码: #!/usr/bin/python f = open('file','r') for line in f: print line print 'Next line ', f.readline() f.close() 这将提供以下输出: This is the first line Next line That was the first line Next line 为什么readline()函数不能在循环中工作?它不应该打印文件的下一行吗? 我使用以
#!/usr/bin/python
f = open('file','r')
for line in f:
print line
print 'Next line ', f.readline()
f.close()
这将提供以下输出:
This is the first line
Next line
That was the first line
Next line
为什么readline()函数不能在循环中工作?它不应该打印文件的下一行吗?我使用以下文件作为输入
This is the first line
That was the first line
您正在搞乱文件迭代的内部状态,因为出于优化原因,对文件进行迭代将以块方式读取它,并对其执行拆分。显式的
readline()
-调用将因此而混淆(或混淆迭代)
要实现所需的功能,请使迭代器显式:
import sys
with open(sys.argv[1]) as inf:
fit = iter(inf)
for line in fit:
print "current", line
try:
print "next", fit.next()
except StopIteration:
pass
用这个
for i, line in enumerate(f):
if i == 0 :
print line
else:
print 'NewLine: %s' % line
您使用的是什么版本的Python?当我运行你的代码时,我得到了
ValueError:混合迭代和读取方法会丢失数据
。这在语义上与OPs代码不同(按他遇到的问题计算)。这不会使循环体中的两个连续行可用。@deets确切地说,应该使用。next()