简体   繁体   English

如何在文件python中显示行数

[英]How to display number of lines in a file python

I assume that I have a text file which contains many lines for example: 我假设我有一个包含许多行的文本文件,例如:

fsdfgsfgf
b3cbc3b45
456346aaa
bce45fa45

I want to display each line and it number: 我想显示每一行及其编号:

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)

The result that I want is: 我想要的结果是:

Text: b3cbc3b45
it is number is:2

But What I have as a result is: 但是我的结果是:

Text: b3cbc3b45
it is number is:b3cbc3b45

So how to display the number of a file's line in python ? 那么如何在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)

out: 出:

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

You can use the enumerate command with the readlines() method like this: 您可以将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.

Use with to open file, enumerate to show the line number. 使用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