How can I open multiple files using with open in Python

0 votes

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 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?

Nov 20, 2020 in Python by kartik
• 37,510 points
1,296 views

1 answer to this question.

0 votes

Hello,

Just replace and with , and you're done:

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

Hope it helps!!

answered Nov 20, 2020 by Niroj
• 82,880 points

Related Questions In Python

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,436 views
0 votes
1 answer

Open multiple files using with open() in Python?

Just replace and with , and you're done: with open('a', 'w') as ...READ MORE

answered Oct 31, 2018 in Python by Priyaj
• 58,090 points
8,341 views
0 votes
1 answer

How can I lookup hostname using the IP address with a timeout in Python?

Good question. I actually was stuck with ...READ MORE

answered Feb 6, 2019 in Python by Nymeria
• 3,560 points
2,233 views
0 votes
1 answer

How can I deal with python eggs for multiple platforms in one location?

Try virtualenv : http://pypi.python.org/pypi/virtualenv This helps you create isolated ...READ MORE

answered May 28, 2019 in Python by SDeb
• 13,300 points
700 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,058 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,790 points
3,478 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,880 points
519 views
0 votes
1 answer

How can I find script's directory with Python?

Hii, You need to call os.path.realpath on __file__, so that when __file__ is ...READ MORE

answered May 11, 2020 in Python by Niroj
• 82,880 points
597 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