我有以下代码:
#!/usr/bin/python
f = open('file','r')
for line in f:
print line
print 'Next line ', f.readline()
f.close()
Run Code Online (Sandbox Code Playgroud)
这给出了以下输出:
This is the first line
Next line
That was the first line
Next line
Run Code Online (Sandbox Code Playgroud)
为什么readline()函数在循环中不起作用?它不应该打印文件的下一行吗?
我使用以下文件作为输入
This is the first line
That was the first line
Run Code Online (Sandbox Code Playgroud)
您正在弄乱文件迭代的内部状态,因为出于优化原因,迭代文件将以块为单位读取它,并对其执行拆分.显式readline()-call将被此混淆(或混淆迭代).
要实现您想要的,请使迭代器显式:
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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
653 次 |
| 最近记录: |