read()文本文件的不同输出

时间:2015-12-29 10:18:38

标签: 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

5 个答案:

答案 0 :(得分:6)

问题在于您正在混合两种读取文件的方法。

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())

答案 1 :(得分:1)

要打印整个文件:

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

答案 2 :(得分:0)

for word in apertura.read().split():
    print (word)

答案 3 :(得分:-1)

试试这个:

for line in apertura.readlines():
    print line

这应该有用。

答案 4 :(得分:-1)

打开('C:\ Users \ 33382 \ Desktop \ pf.txt','r')为f:      lines = f.readlines()

换行:      打印线