Looking for a Python Program/Tool That Will Add Line Numbers to a txt File

Steve Holden steve at holdenweb.com
Fri Feb 15 12:46:36 EST 2008


W. Watson wrote:
> Thanks. I found this to work:
> 
> input_file=open('junkin.txt','r')
> output_file=open('junkout.txt','w')
> for (line_cnt, each_line) in enumerate(input_file):
>      output_file.write('%4d '%(line_cnt+1)+each_line)

You can improve this slightly by using string formatting more fully:

     output_file.write("%4d %s" % (line_ct+1, each_line))

> output_file.close()
> input_file.close()
> 
regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list