Open multiple files using with open in Python

0 votes

if I somehow can combine the multiple open calls with the with 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 other way to solve this problem look like?

Oct 31, 2018 in Python by findingbugs
• 3,260 points
8,640 views

1 answer to this question.

0 votes
Just replace and with , and you're done:
with open('a', 'w') as a, open('b', 'w') as b:
    do_something()

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

answered Oct 31, 2018 by Priyaj
• 58,020 points

Related Questions In Python

0 votes
1 answer

How can I open multiple files using “with open” in Python?

Hello, Just replace and with , and you're done: try: ...READ MORE

answered Nov 20, 2020 in Python by Niroj
• 82,840 points
1,519 views
0 votes
1 answer

How can I open multiple files using “with open” in Python?

Hello @kartik, Just replace and with , and you're done: try: ...READ MORE

answered Dec 8, 2020 in Python by Niroj
• 82,840 points
742 views
0 votes
2 answers

How can I rename multiple files in a certain directory using Python?

import os from optparse import OptionParser, Option class MyOption ...READ MORE

answered Jul 29, 2020 in Python by The real slim shady
4,718 views
0 votes
1 answer

How to extract specific tags in multiple html .txt files using python.

Hello, @Pooja, Even I got the same issue, ...READ MORE

answered Aug 5, 2020 in Python by Kedaar Thomas
5,302 views
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,434 views
0 votes
1 answer
+2 votes
3 answers

How can I play an audio file in the background using Python?

down voteacceptedFor windows: you could use  winsound.SND_ASYNC to play them ...READ MORE

answered Apr 4, 2018 in Python by charlie_brown
• 7,720 points
13,544 views
+1 vote
1 answer

How to create plots using python matplotlib in IPython notebook?

I think you should try: I used %matplotlib inline in ...READ MORE

answered Aug 8, 2018 in Python by Priyaj
• 58,020 points
1,574 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP