简体   繁体   中英

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 ?

# 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:

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 open('test.txt') as f:
    for index, line in enumerate(f, 1):
        print 'Text:', line,
        print 'Its number is:', index

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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