Hawraa Alsaba
Hawraa Alsaba

Reputation: 15

reading each line of a text file preceded by line numbers

demoFile=open("lambpoem.txt","r")
for i in demoFile:
    print(i)

how do I modify the code in order for it to include the line number before the text in that line?

Upvotes: 1

Views: 470

Answers (2)

Dmitry Shevchenko
Dmitry Shevchenko

Reputation: 478

Here is an example with enumerate

with open('lambpoem.txt') as f:
    for line in enumerate(f):
        print(f'{line[0] + 1}. {line[1]}')

Upvotes: 3

Ben
Ben

Reputation: 454

The way that I do this but this is certainly not the only way would to do so.

with open('File.txt', 'r') as f:
    files = f.readlines()
for i in range(len(files)):
    print(i, files[i])

Upvotes: 0

Related Questions