How to open multiple files using with open

Asked 2 years ago, Updated 2 years ago, 115 views

You are creating a program that opens and modifies multiple files at once. with I want to open several files per line using the sentence, but it doesn't work because I write it like the code below

I want to write it as short as possible, what should I do?

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

file-io python

2022-09-21 15:52

1 Answers

You wrote it well, but please change and to , (available from Python 2.7)

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


2022-09-21 15:52

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.