On Feb 13, 8:31*pm, 7stud <bbxx789_0...@y ahoo.comwrote:
On Feb 13, 6:47*pm, Robert <robert.p...@gm ail.comwrote:
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.isfi rstline()):
* * * if (fileinput.line no 1):
* * * * *print "%8d lines" % (fileinput.line no()-1)
* * * print "%s" % fileinput.filen ame()
print "%8d lines" % fileinput.filel ineno()
--------------------------------------------------------------------------- ------
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.linen o *v. fileinput.linen o()
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.isfi rstline()):
* * * * print fileinput.linen o *#<-------*****
* * * * if (fileinput.line no 1):
* * * * * * *print "%8d lines" % (fileinput.line no()-1)
* * * * print "%s" % fileinput.filen ame()
print "%8d lines" % fileinput.filel ineno()
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.isfi rstline()):
if (fileinput.line no() 1):
print "%20s has %8d lines" % (file, fileinput.linen o()-1)
file = fileinput.filen ame()
count = fileinput.linen o()-1 # needed this in case there is an
empty file at the end of list
print "%20s has %8d lines" % (file, fileinput.linen o()-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.