如何使用Python中的“open”打开多个文件?

我想同时更改几个文件, 如果我可以写入所有这些文件。 我想知道如果我能以某种方式将多个打开的调用与with语句组合在一起:

 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 

如果这是不可能的,这个问题的优雅解决scheme是什么样的?

从Python 2.7(或3.1分别),你可以写

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

在Python的早期版本中,有时可以使用contextlib.nested()来嵌套上下文pipe理器。 这不会按预期方式打开多个文件 – 请参阅链接的文档的详细信息。

只需要replaceand就完成了:

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

要一次打开多个文件或打开长文件path,可能需要将多行文件分解。 从@Sven Marnachbuild议的Python风格指南到另一个回答:

 with open('/path/to/InFile', 'r') as file_1, \ open('/path/to/OutFile', 'w') as file_2: file_2.write(file_1.read())