我想一次更改几个文件,如果我可以写入所有文件。我想知道我是否可以将多个打开的调用与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

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


当前回答

只需将和替换为,即可完成:

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

其他回答

Python 3.10中有一个带圆括号上下文管理器的新功能,它允许如下语法:

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

对于一次打开多个文件或对于长文件路径,在多行上拆分可能很有用。从@Sven Marnach在评论中建议的Python风格指南到另一个答案:

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

对于python 2.6,它将无法工作,我们必须使用以下方式打开多个文件:

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

从Python 3.3开始,您可以使用contextlib模块中的ExitStack类来安全地打开任意数量的文件。

它可以管理动态数量的上下文感知对象,这意味着如果您不知道要处理多少文件,它将被证明特别有用。

事实上,文档中提到的规范用例是管理动态数量的文件。

with ExitStack() as stack:
    files = [stack.enter_context(open(fname)) for fname in filenames]
    # All opened files will automatically be closed at the end of
    # the with statement, even if attempts to open files later
    # in the list raise an exception

如果您对详细信息感兴趣,下面是一个通用示例,以解释ExitStack是如何操作的:

from contextlib import ExitStack

class X:
    num = 1

    def __init__(self):
        self.num = X.num
        X.num += 1

    def __repr__(self):
        cls = type(self)
        return '{cls.__name__}{self.num}'.format(cls=cls, self=self)

    def __enter__(self):
        print('enter {!r}'.format(self))
        return self.num

    def __exit__(self, exc_type, exc_value, traceback):
        print('exit {!r}'.format(self))
        return True

xs = [X() for _ in range(3)]

with ExitStack() as stack:
    print(len(stack._exit_callbacks)) # number of callbacks called on exit
    nums = [stack.enter_context(x) for x in xs]
    print(len(stack._exit_callbacks))

print(len(stack._exit_callbacks))
print(nums)

输出:

0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]

嵌套语句也会起到同样的作用,而且在我看来,处理起来更简单。

假设您有inFile.txt,并希望同时将其写入两个outFile。

with open("inFile.txt", 'r') as fr:
    with open("outFile1.txt", 'w') as fw1:
        with open("outFile2.txt", 'w') as fw2:
            for line in fr.readlines():
                fw1.writelines(line)
                fw2.writelines(line)

编辑:

我不明白否决的原因。我在发布我的答案之前测试了我的代码,它按预期工作:正如问题所问,它会写入所有outFile。无重复书写或未能书写。所以我很想知道为什么我的答案被认为是错误的、次优的或类似的。