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

Chris cwitts at gmail.com
Thu Feb 14 08:13:16 CET 2008


On Feb 14, 8:54 am, "W. Watson" <wolf_tra... at invalid.com> wrote:
> See Subject. It's a simple txt file, each line is a Python stmt, but I need
> up to four digits added to each line with a space between the number field
> and the text. Perhaps someone has already done this or there's a source on
> the web for it. I'm not yet into files with Python. A sudden need has burst
> upon me. I'm using Win XP.
> --
>                           Wayne Watson (Nevada City, CA)
>
>                         Web Page: <speckledwithStars.net>

enumerate through the file which will yield you a counter (starting @
zero so just add 1) and use the string function .zfill() to pad it out
for you.
eg.

for (line_cnt, each_line) in enumerate(input_file):
    output_file.write(print ('%s '%(line_cnt+1)).zfill(5) + each_line)
output_file.close()
input_file.close()



More information about the Python-list mailing list