我想添加行号,后跟一个冒号标志,以任何文本文件。我正在打开一个文件,然后将其另存为新文件。我的代码工作正常,直到新的文件长度超过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))
答案 0 :(得分: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))