file.readlines() question

Erik Max Francis max at alcyone.com
Sat Jul 9 05:18:17 EDT 2005


vch wrote:

> Does a call to file.readlines() reads all lines at once in the memory? 
> Are the any reasons, from the performance point of view, to prefer 
> *while* loop with readline() to *for* loop with readlines()?

Yes, and you just mentioned it.  .readlines reads the entire file into 
memory at once, which can obviously be expensive if the file is large.

A for loop with .readline, of course, will work, but modern versions of 
Python allow iteration over a file, which will read it line by line:

	for line in aFile:
	    ...

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis
   A wise man never loses anything if he have himself.
   -- Montaigne



More information about the Python-list mailing list