用行号 python 打印出(从文件中)每一行

Pyt*_*112 2 python loops file list

我有一个.txt文档,其中包含一些单词,每个单词位于不同的行上。

例如:

hello
too
me
Run Code Online (Sandbox Code Playgroud)

我试图弄清楚如何打印每一行以及每个单词所在的行号,但从 1 开始,而不是 0 。

所需的输出:

1 = hello
2 = too
3 = me
Run Code Online (Sandbox Code Playgroud)

我已经有了一个从文本文档中获取行的解决方案:

open_file = open('something.txt', 'r')
lines = open_file.readlines()
for line in lines:
    line.strip()
    print(line)
open_file.close()
Run Code Online (Sandbox Code Playgroud)

我知道我可以打印出每个单词所在的索引,但是除非我弄错了,否则行号将从 0 而不是 1 开始。

ssm*_*ssm 7

您应该使用枚举器和迭代器,而不是将整个文件读取到内存中:

with open('something.txt', 'r') as f:
    for i, line in enumerate(f, start=1):
        print('{} = {}'.format(i, line.strip()))
Run Code Online (Sandbox Code Playgroud)

  • 您可以使用 enumerate(f, start=1) 来避免添加。 (2认同)