Adding line numbers to a file in python 3

后端 未结 2 917
囚心锁ツ
囚心锁ツ 2021-01-15 23:06

I need to write the line numbers to an already existing text file in python 3. They have asked for the first 5 columns of the text file to contain a 4 digit line number foll

相关标签:
2条回答
  • 2021-01-15 23:19
    #!/usr/bin/python
    numberedfile = open("test.txt", "r")
    numberedlist = numberedfile.readline()
    i = 0
    for lines in numberdlist:
        i = i+1
        print str(i) + '\t' + lines
    numberdfile.close()
    
    0 讨论(0)
  • 2021-01-15 23:22

    This prints to stdout the text pattern you describe:

    with open('/etc/passwd') as fp:
        for i, line in enumerate(fp):
            sys.stdout.write('%04d %s'%(i, line))
    

    If you need to edit the file in place, or support multiple files, try using fileinput:

    #!/usr/bin/python
    
    import fileinput
    import sys
    
    for line in fileinput.input(inplace=True):
        sys.stdout.write('%04d %s'%(fileinput.filelineno(), line))
    
    0 讨论(0)
提交回复
热议问题