Looking for a Python Program/Tool That Will Add Line Numbers to a txt File
thebjorn
BjornSteinarFjeldPettersen at gmail.com
Mon Feb 18 03:27:15 EST 2008
On Feb 15, 8:55 pm, Jeff Schwab <j... at schwabcenter.com> wrote:
> W. Watson 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.
>
> i = 0
> for line in sys.stdin:
> i += 1
> print i, line,
>
> Or if you want consistent alignment:
>
> i = 0
> for line in sys.stdin:
> i += 1
> print "%4s" % i, line,
I like your version best (it's very clean and easy to understand), but
here's a few more versions...
from itertools import count
for i, line in zip(count(1), open('filename.txt')):
print i, line,
or with consistent alignment:
for x in zip(count(1), open('filename.txt')):
print "%4d %s" % x,
the latter version gives rise to a one-liner
open('output.txt','w').writelines('%4d %s' % x for x in
zip(count(1), open('perms.py')))
but as I said, I like the simple for loop the best ;-)
-- bjorn
More information about the Python-list
mailing list