Adding line numbers to the output in Python

前端 未结 3 766
执念已碎
执念已碎 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))
    
    0 讨论(0)
  • 2020-12-04 04:56

    You should add:

    newFile = open(yourfile, 'w')
    count = 1
    
    for line in readfile:
        newFile.write (str(count) + '\t' + line)
        count += 1
    newFile.close()
    

    If you just want to print to console write (this is according to the variable names you've used in your second edit):

    for lines in openfile:
        print str(count) + '\t' + lines
        count += 1
    

    You should do your homework yourself, though!

    0 讨论(0)
  • 2020-12-04 04:56

    I would write so:

    with open(path) as src:
        for index, line in enumerate(src.readlines(), start=1):
            print '{:4d}: {}'.format(index, line.rstrip())
    

    or

    with open(path) as src:
        print '\n'.join(['{:4d}: {}'.format(i, x.rstrip()) for i, x in enumerate(src.readlines(), start=1)])
    
    0 讨论(0)
提交回复
热议问题