reading a text file

Peter Otten __peter__ at
Wed Aug 19 11:08:06 CEST 2009

superpollo wrote:

> hi clp
> what's the difference between:
> while True:
>      input_line = sys.stdin.readline()
>          if input_line:
>              sys.stdout.write(input_line.upper())
>          else:
>              break
> and:
> while True:
>      try:
>          sys.stdout.write(
>      except StopIteration:
>          break

You should write the latter as

for line in sys.stdin:


sys.stdout.writelines(line.upper() for line in sys.stdin)

You seem to know already that next() and readline() use different ways to 
signal "I'm done with the file". Also, after the first StopIteration 
subsequent next() calls are guaranteed to raise a StopIteration. But the 
main difference is that uses an internal buffer, file.readline() 
doesn't. That means you would lose data if you tried to replace the 
readline() call below with next()

first_line = f.readline()
read_of_the_file =

In newer Python versions you will get a ValueError when mixing next() and 
read()/readline() but in older Pythons (before 2.5 I think) you are in for a 


for line in file: ...

is both the fastest and most readable approach if you want to access a file 
one line at a time I recommend that you use it unless there is a specific 
reason not to.


More information about the Python-list mailing list