且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

将行号添加到 Python 中的输出

更新时间:2023-12-01 08:29:16

使用 with 语句关闭文件缓冲区并只连接字符串:

Use a with statement to close the file buffer and just concatenate strings:

with open('file.txt', 'r') as program:
    data = program.readlines()

with open('file.txt', 'w') as program:
    for (number, line) in enumerate(data):
        program.write('%d  %s' % (number + 1, line))