Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
1 view
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 (108k points)

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()

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
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.2k users

Browse Categories

...