read()文本fi的不同输出

2024-09-28 21:02:28 发布

您现在位置:Python中文网/ 问答频道 /正文

此代码的结果:

!/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

Tags: 文件代码fromreadbinusrfileargv
3条回答
for word in apertura.read().split():
    print (word)

问题是您混合了两种读取文件的方法

for a in apertura:          # this reads in the first line of the file
    print(apertura.read())  # this reads the remainder of the file in one chunk

所以文件的第一行永远不会被打印出来

您可以像这样逐行遍历文件:

for a in apertura:
    print(a)

您还可以使用上下文管理器来确保文件在之后关闭

#!/usr/bin/python
from sys import argv
script, file = argv
with open(file, 'r') as apertura:
    for a in apertura:
        print(a)

如果您真的想使用.read()读取文件,那么代码稍微简单一些,但是在文件很大的情况下会占用大量内存

#!/usr/bin/python
from sys import argv
script, file = argv
with open(file, 'r') as apertura:
    print(apertura.read())

要打印整个文件:

!/usr/bin/python
from sys import argv
script, file = argv
apertura = open(file,'r')
print apertura.read()

或更短:

!/usr/bin/python
import sys
print open(sys.argv[1]).read()

相关问题 更多 >