Adding line numbers to the output in Python

前端 未结 3 770
执念已碎
执念已碎 2020-12-04 04:26

For example, if the input file is:

def main():
    for i in range(10):
        print("I love Python")
    print("Good bye!")
3条回答
  •  醉酒成梦
    2020-12-04 04:54

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

提交回复
热议问题