testing true condition

Michael P. Reilly arcege at shore.net
Wed Apr 19 08:09:38 EDT 2000


Remco Gerlich <scarblac-spamtrap at pino.selwerd.nl> wrote:
: Gregoire Welraeds wrote in comp.lang.python:
:> I know that I can't do something like the following:
:> 
:> >>> while (line= f.readline()):
:> 	...
:> 
:> as i could in C.  Is there any replacement tricks ?

: The standard Python idiom is:

: while 1:
:    line = f.readline()
:    if not line:
:       break

This is only one of the two, simple, "standard" idioms, the other is:

>>> line = f.readline()
>>> while line:
...   ...
...   line = f.readline()
...

(Many ppl do not like, with reasons, the `if not line: break'
construct, but all that is in past debates on this NG available
somewhere on dejanews.com.)

Since the original poster also had a fear of reading in the entire
file, the readlines() method can also be used with improved performance
in a slightly more complex fashion:

>>> for list_of_lines in f.readlines(16384):  # read in 16k at a time
...   for line in list_of_lines:
...     ...
...

This is more efficient when you have a large text file to read, but do
not want to read the entire file.  Sets of pages are read in at a time
and split into the lines.  The size passed to readlines may need to be
adjusted on the end machine.  The fileinput module will not be as
efficient (at least in 1.5.2, not sure about 1.6a).

  -Arcege




More information about the Python-list mailing list