且构网

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

如何将行号添加到输出文件?

更新时间:2023-12-03 07:53:28

First, it is best to use the with ... syntax when using files (https://docs.python.org/2/tutorial/inputoutput.html).

Then, all you have to do is use enumerate (https://docs.python.org/2/library/functions.html#enumerate). enumerate is a built-in function that takes a sequence (string, list, dict, set, ...) as input and generates tuples with a counter and the corresponding value of the sequence.

with open(filename, "r") as openfile:
    with open(filename2, "w") as out_file:
        for j, line in enumerate(openfile):
            out_file.write('{0:<5}{1}'.format(j+1, line))

相关阅读

推荐文章