David Wojcik
David Wojcik

Reputation: 53

Can't figure out how to add line numbers to text file

I need to take a text file and import it to python, write the text inside that file to a new file and include line numbers on each line inside that text file.

I figured out how to write the original text to a new file but I am stuck on where to start to add in line numbers on each line.

text = open('lab07_python.txt', 'r')
make = text.read()
text.close()

new = open('david.txt', 'w')
new.write(make)
new.close()

Upvotes: 1

Views: 371

Answers (2)

amaurs
amaurs

Reputation: 1642

You need to iterate over the lines of the old file, something like:

with open('lab07_python.txt', 'r') as old:
    lines = old.readlines()
    with open('david.txt', 'w') as new:
        for i, line in enumerate(lines):
            new.write("%d %s\n" % (i, line))

Upvotes: 1

David Wojcik
David Wojcik

Reputation: 53

Solved by adding some string formatting:

total = 0
with open('lab07_python.txt', 'r') as orig:
    lines = orig.readlines()
    for line in lines:
        total = total +1
        new = '%d %s' % (total, line)
        david.write(new)

Upvotes: 0

Related Questions