user3339672
user3339672

Reputation: 31

Prepend line number to string in python

I have a text file in the following format:

"This is record #1"
"This is record #2"
"This is record #3"

I need the output in the following format:

Line number (1) --\t-- "This is Record # 1"
2-- \t-- "This is Record # 2"
3-- \t-- "This is Record # 3" 

Current code:

f = open("C:\input.txt","r")
write_file = open("C:\output.txt","r+")
while True:
    line = f.readline()
    write_file.write(line)
    if not line : break
write_file.close()
f.close()

Upvotes: 2

Views: 443

Answers (2)

tutuDajuju
tutuDajuju

Reputation: 10870

Your code was pretty close to the target:

# open the file for reading
f = open("C:\input.txt","r")

# and a file for writing
write_file = open("C:\output.txt","r+")

for i, line in enumerate(f):
    line = f.readline()
    mod_line = "%s-- \t-- %s" % (i, line)  # 1-- \t-- "This is Record # 1"
    write_file.write(mod_line)

write_file.close()
f.close()

Upvotes: 2

crunch
crunch

Reputation: 675

Try traversing your file this way:

f = open('workfile', 'r')
for num,line in enumerate(f):
    print(num+" "+line)

Upvotes: 5

Related Questions