使用python从文本文件中读取 - 错过了第一行

Rid*_*dle 4 python file-io

我有一个名为test的文件,其中包含以下内容:

a
b
c
d
e
f
g
Run Code Online (Sandbox Code Playgroud)

我使用以下python代码逐行读取此文件并将其打印出来:

with open('test.txt') as x:
    for line in x:
        print(x.read())
Run Code Online (Sandbox Code Playgroud)

结果是打印出除第一行之外的文本文件的内容,即结果是:

b
c
d
e
f
g 
Run Code Online (Sandbox Code Playgroud)

有没有人知道为什么它可能会丢失文件的第一行?

jam*_*lak 8

因为for line in x遍历每一行.

with open('test.txt') as x:
    for line in x:
        # By this point, line is set to the first line
        # the file cursor has advanced just past the first line
        print(x.read())
        # the above prints everything after the first line
        # file cursor reaches EOF, no more lines to iterate in for loop
Run Code Online (Sandbox Code Playgroud)

也许你的意思是:

with open('test.txt') as x:
    print(x.read())
Run Code Online (Sandbox Code Playgroud)

一次打印,或:

with open('test.txt') as x:
    for line in x:
        print line.rstrip()
Run Code Online (Sandbox Code Playgroud)

逐行打印.建议使用后者,因为您不需要立即将文件的全部内容加载到内存中.