此代码的结果:
!/usr/bin/python
from sys import argv
script, file = argv
apertura = open(file,'r')
for a in apertura:
print(apertura.read())
是:
quarta quinta
sesta
settima
ottava
nona
我想用read()打印整个文件。上面的代码跳过了一些行。为什么
文件内容如下:
prima seconda terza
quarta
quinta
sesta
settima
ottava
nona
问题是您混合了两种读取文件的方法
所以文件的第一行永远不会被打印出来
您可以像这样逐行遍历文件:
您还可以使用上下文管理器来确保文件在之后关闭
如果您真的想使用
.read()
读取文件,那么代码稍微简单一些,但是在文件很大的情况下会占用大量内存要打印整个文件:
或更短:
相关问题 更多 >
编程相关推荐