如何显示python文件中的行数

如何显示python文件中的行数,python,Python,我假设我有一个包含许多行的文本文件,例如: fsdfgsfgf b3cbc3b45 456346aaa bce45fa45 我想显示每一行及其编号: text_file = open(r'C:\\Users\\user\\Text.txt', 'r') for a in Plaintxt_file: text=a[0:9] print ('Text:', text ) print('it is number is:', a) 我想要的结果是: Text: b3cbc3

我假设我有一个包含许多行的文本文件,例如:

fsdfgsfgf
b3cbc3b45
456346aaa
bce45fa45
我想显示每一行及其编号:

text_file = open(r'C:\\Users\\user\\Text.txt', 'r')
for a in Plaintxt_file:
    text=a[0:9]
    print ('Text:', text )
    print('it is number is:', a)
我想要的结果是:

Text: b3cbc3b45
it is number is:2
但结果是:

Text: b3cbc3b45
it is number is:b3cbc3b45

那么,如何在python中显示文件的行号呢

您可以将
enumerate
命令与
readlines()
方法一起使用,如下所示:

f = open('test.txt', 'r')
for index, line in enumerate(f.readlines()):
     # index represents the index of the line and line the line in the file.
输出:


使用
打开文件,
枚举
显示行号

with open('test.txt') as f:
    for index, line in enumerate(f, 1):
        print 'Text:', line,
        print 'Its number is:', index

因为您的文本变量正在访问文件行的索引,而不是行号。
Text: fsdfgsfgf
it is number is: 1
Text: b3cbc3b45
it is number is: 2
Text: 456346aaa
it is number is: 3
Text: bce45fa45
it is number is: 4
with open('test.txt') as f:
    for index, line in enumerate(f, 1):
        print 'Text:', line,
        print 'Its number is:', index