How to add line numbers to an output file?

拥有回忆 提交于 2019-12-29 08:23:58

问题


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 file. For example, if the input file is:

def main():
    for i in range(10):
        print("I love python")
    print("Good bye!")

Then the output file would be:

1   def main():
2       for i in range(10):
3           print("I love python")
4       print("Good bye!")

I know how to create a new output file but I have difficulty in adding line numbers to each line. please help! My program is:

filename = input("Please enter a file name: ")
filename2 = input("Please enter a file name to save the output: ")

openfile = open(filename, "r")
readfile = openfile.readlines()


out_file = open(filename2, "w")
save = out_file.write(FileWithLines)

回答1:


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))



回答2:


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



来源:https://stackoverflow.com/questions/29267986/how-to-add-line-numbers-to-an-output-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!