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