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

W. Watson wolf_tracks at invalid.com
Thu Feb 14 17:50:45 CET 2008

Thanks. I found this to work:

for (line_cnt, each_line) in enumerate(input_file):
     output_file.write('%4d '%(line_cnt+1)+each_line)

I removed the print, but ran into trouble with zfill. I thought this might 
be more difficult judging by a long ago experience with Java.

Chris wrote:
> On Feb 14, 1:29 pm, John Machin <sjmac... at lexicon.net> wrote:
>> 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?
> print was a typo
> take a look at the string that is built before the zfill fires, it has
> a trailing space so it is correct. ;)

                          Wayne Watson (Nevada City, CA)

                        Web Page: <speckledwithStars.net>

More information about the Python-list mailing list