相关疑难解决方法(0)

我应该如何在Python中逐行读取文件?

在史前时期(Python 1.4),我们做到了:

fp = open('filename.txt')
while 1:
    line = fp.readline()
    if not line:
        break
    print line
Run Code Online (Sandbox Code Playgroud)

在Python 2.1之后,我们做了:

for line in open('filename.txt').xreadlines():
    print line
Run Code Online (Sandbox Code Playgroud)

在我们在Python 2.3中获得方便的迭代器协议之前,可以做到:

for line in open('filename.txt'):
    print line
Run Code Online (Sandbox Code Playgroud)

我见过一些使用更详细的例子:

with open('filename.txt') as fp:
    for line in fp:
        print line
Run Code Online (Sandbox Code Playgroud)

这是前进的首选方法吗?

[编辑]我得到了with语句确保关闭文件...但为什么不包含在文件对象的迭代器协议中?

python python-2.7 python-3.x

132
推荐指数
3
解决办法
32万
查看次数

标签 统计

python ×1

python-2.7 ×1

python-3.x ×1