john
john

Reputation: 125

python add numbers in front of lines and export it to a new file

i have a file(A.txt) that it has a series of lines. i would like to read file(A) and create a new file(B) and add a number and a semicolon at the beginning and a space before the text of each line. at the moment i have:

with open('A.txt','r+') as f:
for index, line in enumerate(f.readlines(), start=1):
    print('{:4d}: {}'.format(index, line.rstrip()))

the above code takes the file(A) and adds the number in the format i want. The problem is that i do not know how to leave file(A.txt), just read the contents of A.txt, as it is and make all changes to file(B.txt). Any ideas, please?

Upvotes: 0

Views: 1200

Answers (1)

sebasth
sebasth

Reputation: 997

Open file B in write-mode, open("B.txt", "w"), then instead of calling print, call write on the new file descriptor.

with open("A.txt", "r") as a, open("B.txt", "w") as b:
    b.write(...)

Your program would look like:

with open("A.txt", "r") as a, open("B.txt", "w") as b:
    index = 1
    for line in a:
        b.write("{:4d}: {}\n".format(index, line.rstrip()))
        index += 1

Upvotes: 1

Related Questions