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

John Machin sjmachin at lexicon.net
Thu Feb 14 06:29:24 EST 2008


On Feb 14, 6:13 pm, Chris <cwi... at gmail.com> wrote:
> 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)

(1) What's that "print" doing in there?
(2) zfill(5)? The OP asked for "up to 4 digits", not 5.
(2) As an alternative to str.zfill, consider using formatting:

output_file.write('%04d %s' % (line_cnt+1, each_line))

And what does "up to 4" mean? What does the OP want the 10000th line
to look like?




More information about the Python-list mailing list