【问题标题】:add line numbers and a colon to a file向文件添加行号和冒号
【发布时间】:2019-02-02 21:35:01
【问题描述】:

我正在尝试向任何文本文件添加行号,后跟冒号。我正在打开一个文件,然后将其另存为一个新文件。我的代码工作正常,直到新文件超过 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】:

    如果您不介意行 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))
    

    【讨论】:

      猜你喜欢
      • 2015-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-15
      • 1970-01-01
      • 2016-01-27
      • 1970-01-01
      • 2021-10-21
      相关资源
      最近更新 更多