How to count lines in a text file ?

Bengt Richter bokr at oz.net
Wed Sep 22 19:59:30 CEST 2004


On Mon, 20 Sep 2004 15:29:18 +0200, aleaxit at yahoo.com (Alex Martelli) wrote:

>Ling Lee <janimal at mail.trillegaarden.dk> wrote:
>
>> Oh I just did it.
>> 
>> Just used the line:
>> 
>> print "%d lines in your choosen file" % len(open("test.txt").readlines())
>> 
>> Thanks though :)
>
>You're welcome;-).  However, this approach reads all of the file into
>memory at once.  If you must be able to deal with humungoug files, too
>big to fit in memory at once, try something like:
>
>numlines = 0
>for line in open('text.txt'): numlines += 1

I don't have 2.4, but how would that compare with a generator expression like (untested)

    sum(1 for line in open('text.txt'))

or, if you _are_ willing to read in the whole file,

    open('text.txt').read().count('\n')

Regards,
Bengt Richter



More information about the Python-list mailing list