Newbie Needs help!!

Michael Geary Mike at DeleteThis.Geary.com
Fri Oct 10 15:04:23 EDT 2003


Rigga wrote:
> Thanks for your reply, I was under the misunderstanding that I
> could read the contents of the file and get the total number of
> lines the file contains in one go.  Any pointers to how I can count
> the lines manually??

You actually can do the whole thing in one line of code:

print len( file('testfile').readlines() )

I think that leaves the file open until the file object gets garbage
collected, though, so it's better to explicitly close the file as you did in
your original code.

Also, readlines() reads the entire file into a list, which of course will
use enough memory to hold the entire file. Of course, depending on what else
you're doing with the file, it may be handy to have all of the file lines in
a list. But if you just want to get the line count with minimal memory
overhead, you can write your own loop:

def countLines( filename ):
    lines = 0
    f = file( filename )
    while f.readline():
        lines += 1
    f.close()
    return lines

print countLines( 'testfile' )

-Mike






More information about the Python-list mailing list