添加行号和冒号文件

问题描述 投票:0回答:1

我想添加行号,后跟一个冒号标志,以任何文本文件。我打开一个文件,然后我将其保存为一个新文件。我的代码工作正常,直到新的文件长度超过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))
python-3.x file line-numbers
1个回答
1
投票

如果你不介意没有行对齐,当您去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))
© www.soinside.com 2019 - 2024. All rights reserved.