Reputation: 79
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
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