Newbie Needs help!!

Rigga Rigga at noemail.com
Fri Oct 10 17:04:17 EDT 2003


Michael Geary wrote:

> 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
Thank you for your help its appreciated.

Im struggling to get to grips with Python at the moment, what I am trying to
do is write a routine that will basically list the current directory (which
contains sub folders) and store all folder names in an array or text file
and then split the each folder name out as fileds (and assign them to
variables) and then run an external program (from within python)  and pass
it fields as input to it..

Early days I guess but im having fun!

Cheers

Rigga




More information about the Python-list mailing list