简体   繁体   English

读取文件并逐行打印python

[英]reading through a file and printing line by line python

I have a file with different planets written on each line. 我有一个文件,每行上写有不同的行星。 I'm trying to iterate through it using the with function and print so the the output looks like this: 我正在尝试使用with函数遍历它并打印,因此输出看起来像这样:

1 - mercury
2 - venus 
etc...

but my output currently looks like this: 但是我的输出当前看起来像这样:

(1, '-', <open file 'planets.txt', mode 'r' at 0x7f87dea69660>)
(2, '-', <open file 'planets.txt', mode 'r' at 0x7f87dea69660>)
(3, '-', <open file 'planets.txt', mode 'r' at 0x7f87dea69660>)
(4, '-', <open file 'planets.txt', mode 'r' at 0x7f87dea69660>)

my code is this: 我的代码是这样的:

with open("planets.txt") as p:
    i=0
    for line in p:
        i += 1
        print(i, '-', p)

How am I using with wrong or is it something else? 我怎么用错了?还是其他?

Instead of printing the line you print p - the file itself: 不用打印line而是打印p文件本身:

    print(i, '-', p)

Also, instead of making a new variable to count lines, you may use enumerate feature: 另外,您可以使用枚举功能代替创建一个新的变量来计算行数:

with open("planets.txt") as p:
    for i, line in enumerate(p, 1):
        print(i, '-', line)

UPD: You should also consider the fact, that the line you are getting from the file ends with a newline character and when you print(line) it adds another newline after it by defaulf. UPD:你也应该考虑这样一个事实,那line ,你是从文件中获取一个换行符结束,当你print(line)它通过defaulf后增加了一个换行符。 So your output will look like that: 因此您的输出将如下所示:

1 - mercury

2 - venus 

etc...

to get 要得到

1 - mercury
2 - venus 
etc...

you need to specify end='' argument to print function. 您需要为打印功能指定end=''参数。 This way: 这条路:

        print(i, '-', line, end='')

You want to print line not p : 您要打印的line不是p

with open("planets.txt") as p:
    i=0
    for line in p:
        i += 1
        print(i, '-', line) #refers to each line in p rather than the file handler

您应该将print(i, '-', p)更改为print(i, '-', line)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM