open two files at once

Peter Otten __peter__ at
Sat Aug 21 14:57:19 CEST 2010

robek wrote:

> what is the simplest way to open two files (one for reading and 2nd for
> writing) ?
> i usually do:
> with open('1') as f1:
>    with open('2','w') as f2:
>      for i in f1: do something with i
>        f2.write(i)
> is there a simpler/better way to do this ?

Yours is the best way to do it in Python 2.6. In particular, don't use 

Python 2.7 allows writing

with open(source) as f1, open(dest, "w") as f2:
    # ...

saving you one level of indentation.


More information about the Python-list mailing list