使用 python 从文本文件读取 - 第一行被遗漏

2023-12-25

我有一个名为 test 的文件,其内容为:

a
b
c
d
e
f
g

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

with open('test.txt') as x:
    for line in x:
        print(x.read())

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

b
c
d
e
f
g 

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


Because 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

也许你的意思是:

with open('test.txt') as x:
    print(x.read())

一次打印全部内容,或者:

with open('test.txt') as x:
    for line in x:
        print line.rstrip()

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

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 python 从文本文件读取 - 第一行被遗漏 的相关文章

随机推荐