Clueless
Clueless

Reputation: 79

add line numbers and a colon to a file

I'm trying to add line numbers followed by a colon sign to any text file. I'm opening a file and then I'm saving it as a new file. My code works fine until the new file is longer than 10 lines, the the colon disappears. I've tried adding more spaces, but that only ads more colons. Can anyone help with this? Thank you very much

with open(filename, "r") as openfile:
   with open(filename2, "w") as out_file:
      for index, line in enumerate(openfile):
         out_file.write('{0::<2} {1}'.format(index+1, line))

Upvotes: 0

Views: 343

Answers (1)

Andr&#233; C. Andersen
Andr&#233; C. Andersen

Reputation: 9405

If you don't mind lines not being aligned as you go 10, 100, 1000, etc.:

with open(filename, "r") as openfile:
   with open(filename2, "w") as out_file:
      for index, line in enumerate(openfile):
         out_file.write('{0}: {1}'.format(index+1, line))

Upvotes: 1

Related Questions