9

How do i use the with statement in this case?

f_spam = open(spam,'r')
f_bar = open(eggs,'r')
...
do something with these files
...
f_spam.close()
f_bar.close()

Files number could be greater than two.

2 Answers 2

18

You can also do:

from contextlib import nested

with nested(open(spam), open(eggs)) as (f_spam, f_eggs):
    # do something

In Python 2.7 and 3.1+ you don't need the nested function because with supports the following syntax:

with open(spam) as f_spam, open(eggs) as f_eggs:
    # do something
Sign up to request clarification or add additional context in comments.

2 Comments

how would u do it in Python 3?
with open(spam) as f_spam, open(eggs) as f_eggs:.................. See the fourth bullet point down at docs.python.org/release/3.1/whatsnew/…
3
with open(spam,'r') as f_spam:
  with open(eggs,'r') as f_bar:
    #do stuff with each

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.