向文件添加行号和冒号

add line numbers and a colon to a file

我正在尝试向任何文本文件添加行号后跟冒号。我正在打开一个文件,然后将其另存为一个新文件。我的代码工作正常,直到新文件超过 10 行,冒号消失。我试过添加更多空格,但那只会增加更多冒号。有人能帮忙吗?非常感谢

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))

如果您不介意在进行 10、100、1000 等时未对齐线条:

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))