1

I have this bit of one-time-use code, extracted from a function to delete tens of thousands of directories and their contents. It's fine, but I'm wondering if I can use "with open() as" on a bunch of files without indenting and indenting and indenting...

with open(deleted_dirs, 'w') as out_removed:
    with open(unsuccessful_targets, 'w') as out_fail:
        with open(already_gone, 'w') as out_nowhere:
            for target in targets:
                try:
                    shutil.rmtree(target, ignore_errors=False, onerror=on_fail_rmtree)
                    print(target, file=out_removed)
                except FileNotFoundError:
                    print(target, file=out_nowhere)
                except PermissionError:
                    logger.warning('Permission Error: {}'.format(target))
                    print(target, file=out_fail)
return

This question does touch on the same topic as python: create a "with" block on several context managers. The two should be linked, however two important things make this question distinct. 1) This question uses the canonical example of the use of the context manager: "with open(f) as fd:" versus mention of "lock" objects obtainable from a context manager, (obviously the same but not so obviously) and what is more important 2) A diligent search failed to bring up the earlier question or its answers. (Possibly this was made more difficult by the absolute ubiquity of 'with', 'as', 'context', and 'manager' as poor search terms, and that the keyword "contextmanager" is unguessable.)

Community
  • 1
  • 1
mohawkTrail
  • 606
  • 1
  • 7
  • 19
  • Maybe a question for Stack Exchange Code Review? – palsch Apr 15 '16 at 21:51
  • 2
    Possible duplicate of [python: create a "with" block on several context managers](http://stackoverflow.com/questions/3024925/python-create-a-with-block-on-several-context-managers) – Chad S. Apr 15 '16 at 21:52
  • Thanks for pointing out the related question. Good connection. I didn't find it my search. – mohawkTrail Apr 16 '16 at 01:34

1 Answers1

3

It's pretty simple. Example of opening three files for writing:

with open('file1', 'w') as f1, open('file2', 'w') as f2, open('file3', 'w') as f3:
    # do stuff
timgeb
  • 76,762
  • 20
  • 123
  • 145