number of lines in a file

Bengt Richter bokr at oz.net
Fri Mar 29 20:58:59 EST 2002


On 29 Mar 2002 13:22:28 -0800, sjmachin at lexicon.net (John Machin) wrote:

>"Joseph Youssef" <leader730 at hotmail.com> wrote in message news:<b0%o8.22778$Li5.504465 at weber.videotron.net>...
>> hello, I am nwe to Python and I'm trying to write this script but I need 
>> it to check how many lines is in the file and I don't know how so I'm 
>> hoping someone could tell me.
>> 
>
>Welcome to Python. 
>
>Others have suggested approaches which attempt to read the whole file
>into memory, but may succeed very slowly or not at all in the event
>that you have files that are larger than your machine's physical
>memory; here's a slightly more robust approach:
>
>num_lines = 0
>f = file('path_and_file_name')
>for line in f:
>    num_lines += 1
>f.close()
>
You can do a one-liner without reading the whole file at once ;-)

reduce(lambda x,y: x+1, file('/path/and/filename').xreadlines(), 0)

Regards,
Bengt Richter



More information about the Python-list mailing list