number of lines in a file

John Machin sjmachin at lexicon.net
Fri Mar 29 16:22:28 EST 2002


"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()

HTH,
John



More information about the Python-list mailing list