open two files at once

R

robek

hi,
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 ?
 
P

Peter Otten

robek said:
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
contextlib.nested():

http://docs.python.org/library/contextlib.html#contextlib.nested

Python 2.7 allows writing

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

saving you one level of indentation.

Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,997
Messages
2,570,241
Members
46,831
Latest member
RusselWill

Latest Threads

Top