Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
2 views
in Python by (50.2k points)

I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the with a statement:

try: with open('a', 'w') as a and open('b', 'w') as b: do_something() except IOError as e: print 'Operation failed: %s' % e.strerror

If that's not possible, what would an elegant solution to this problem look like?

2 Answers

+2 votes
by (106k points)
edited by

Actually, you are following the correct way to open multiple files in Python in the only thing you need to do is, replace ‘and’ with ‘,’ and you are done with your answer:-.

try: 

with open('a', 'w') as a, open('b', 'w') as b:

 do_something() 

except IOError as e:

  print('Operation failed: %s' % e.strerror)

To know more about this you can have a look at the following video:-

+2 votes
by (107k points)
edited by

In previous versions of Python, you can use contextlib.nested() to nest context managers. 

In your case, just replace 'and' with ',' and you're done:

with open('a', 'w') as a, open('b', 'w') as b:

    do_something()

Be a Python Expert. Enroll in Python Programming Course by Intellipaat! 

Related questions

+2 votes
3 answers
0 votes
1 answer
0 votes
1 answer
asked Jul 18, 2019 in Python by Sammy (47.6k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...