with statement for two files

Diez B. Roggisch deets at nospam.web.de
Sun Jul 27 17:35:06 EDT 2008


braver schrieb:
> Can open two files in a with statement:
> 
> with open(src) as readin, open(dst,"w") as writin:   # WRONG: comma
> doesn't work
>   ...
> 
> -- so that you have transactional safety for two file descriptors?
> The comma syntax doesn't work, but is there a way, except for
> 
> with open(src) as readin:
>   with open(dst,"w) as writin:
>     ...

I'm not aware of any pre-defined context manager which does that.
But you can write your own context manager to do that, even a 
generalized combinator for taking two managers and create one, like this:

with context_creator(open, [src], open, [dst, "w"]) as readin, writin:
      ...

A fundamental problem though would be that the semantics become 
difficult. If closing the "outer" file fails, it's impossible to 
"rollback" the inner one.

So I think it really is better to use the nested with, which makes it 
crystal clear that the inner block might succeed independently from the 
outer one.

Diez



More information about the Python-list mailing list