How to add line numbers to an output file?

后端 未结 2 984
傲寒
傲寒 2020-12-20 08:53

Write a program that asks the user for a file containing a program and a name for an output file. Your program should then write the program, with line numbers to the output

相关标签:
2条回答
  • 2020-12-20 09:25

    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))
    
    0 讨论(0)
  • 2020-12-20 09:26

    Check out this question, it describes exactly what you're looking for. Let me know if you need more details.

    0 讨论(0)
提交回复
热议问题