Robert
2/14/2008 3:10:00 AM
On Feb 13, 8:31 pm, 7stud <bbxx789_0...@yahoo.com> wrote:
> On Feb 13, 6:47 pm, Robert <robert.p...@gmail.com> wrote:
>
>
>
> > I would like to count lines in a file using the fileinput module and I
> > am getting an unusual output.
> > --------------------------------------------------------------------------- ---
> > #!/usr/bin/python
> > import fileinput
>
> > # cycle through files
> > for line in fileinput.input():
> > if (fileinput.isfirstline()):
> > if (fileinput.lineno > 1):
> > print "%8d lines" % (fileinput.lineno()-1)
> > print "%s" % fileinput.filename()
> > print "%8d lines" % fileinput.filelineno()
> > --------------------------------------------------------------------------- ------
>
> > This works fine except it prints "0 lines" first.
> > Can anyone help me understand why that is?
>
> if '<function lineno at 0x57e70>' > 1:
> print 'yes'
>
> --output:--
> yes
>
> fileinput.lineno v. fileinput.lineno()
>
> Whenever you have strange problems like that, insert a bunch of print
> statements to verify that the values are what you think they should
> be:
>
> for line in fileinput.input():
> print line #<-------*****
> if (fileinput.isfirstline()):
> print fileinput.lineno #<-------*****
> if (fileinput.lineno > 1):
> print "%8d lines" % (fileinput.lineno()-1)
> print "%s" % fileinput.filename()
> print "%8d lines" % fileinput.filelineno()
Thanks for the heads up. I hate it when that happens. Anyway, here is
the modified code:
-------------------------------------------------------
#!/usr/bin/python
import fileinput
file = ''
count = 0
# cycle through files
for line in fileinput.input():
if (fileinput.isfirstline()):
if (fileinput.lineno() > 1):
print "%20s has %8d lines" % (file, fileinput.lineno()-1)
file = fileinput.filename()
count = fileinput.lineno()-1 # needed this in case there is an
empty file at the end of list
print "%20s has %8d lines" % (file, fileinput.lineno()-count) # this
is for the last file
--------------------------------------------------------
I added count to keep track of the next to last file in the command
line list. The fileinput module opens then closes an empty file. If
there is a cleaner way to do something like this I would interested to
know. Thanks.