繁体   English   中英

如何在文件python中显示行数

[英]How to display number of lines in a file 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: b3cbc3b45
it is number is:2

但是我的结果是:

Text: b3cbc3b45
it is number is:b3cbc3b45

那么如何在python中显示文件的行数呢?

# with open(filename) as file:
#     for index, line in enumerate(file,1)
file = ['fsdfgsfgf','b3cbc3b45','456346aaa','bce45fa45']
for index, line in enumerate(file,1):
    print ('Text:', line )
    print('it is 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

您可以将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打开文件, enumerate显示的行数。

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

暂无
暂无

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

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