Edit text file to add row numbers (begins in 1 ) - Python

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • mcff
    New Member
    • Dec 2012
    • 2

    Edit text file to add row numbers (begins in 1 ) - Python

    If this is the input:
    a
    b
    c

    I want to have this:
    1 a
    2 b
    3 c

    I have this code:
    Code:
    infile=open('resultado.txt','r')
    lines=infile.readlines()
    infile.close()
    outtext=['%d %s' % (i,line) for i, line in enumerate(lines)]
    outfile = open ('res.txt','w')
    outfile.write(str(''.join(outtext)))
    outfile.close()
    but my row number begins in 0
    Last edited by bvdet; Dec 3 '12, 04:31 PM. Reason: Please use code tags when posting code.
  • mcff
    New Member
    • Dec 2012
    • 2

    #2
    Sorry it was easy, I just added i+1:
    Code:
    infile=open('resultado.txt','r')
    lines=infile.readlines()
    infile.close()
    outtext=['%d %s' % (i+1,line) for i, line in enumerate(lines)]
    outfile = open ('res.txt','w')
    outfile.write(str(''.join(outtext)))
    outfile.close()
    Last edited by bvdet; Dec 3 '12, 04:32 PM. Reason: Please use code tags when posting code.

    Comment

    • bvdet
      Recognized Expert Specialist
      • Oct 2006
      • 2851

      #3
      Instead of (i,line), use (i+1,line).

      Comment

      Working...