Reading from a text file with python - first line being missed

狂风中的少年 提交于 2020-01-23 07:55:13

问题


I have a file called test which has the contents:

a
b
c
d
e
f
g

I am using the following python code to read this file line by line and print it out:

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

The result of this is to print out the contents of the text file except for the first line, i.e. the result is:

b
c
d
e
f
g 

Does anyone have any idea why it might be missing the first line of the file?


回答1:


Because for line in x iterates through every line.

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

Perhaps you meant:

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

to print it all at once, or:

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

to print it line by line. The latter is recommended since you don't need to load the whole contents of the file into memory at once.



来源:https://stackoverflow.com/questions/17237464/reading-from-a-text-file-with-python-first-line-being-missed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!