如何使用“with open"打开多个文件?在 Python 中? [英] How can I open multiple files using "with open" in Python?
问题描述
我想一次更改几个文件,如果我可以写入所有文件.我想知道我是否可以将多个 open 调用与 with
语句结合起来:
I want to change a couple of files at one time, iff I can write to all of them. I'm wondering if I somehow can combine the multiple open calls with the with
statement:
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
如果这是不可能的,那么这个问题的优雅解决方案会是什么样的?
If that's not possible, what would an elegant solution to this problem look like?
推荐答案
从 Python 2.7(或分别为 3.1)开始,您可以编写
As of Python 2.7 (or 3.1 respectively) you can write
with open('a', 'w') as a, open('b', 'w') as b:
do_something()
在早期版本的 Python 中,有时可以使用contextlib.nested()
嵌套上下文经理.但是,这在打开多个文件时不会按预期工作——有关详细信息,请参阅链接的文档.
In earlier versions of Python, you can sometimes use
contextlib.nested()
to nest context managers. This won't work as expected for opening multiples files, though -- see the linked documentation for details.
在极少数情况下,您想同时打开可变数量的文件,您可以使用 contextlib.ExitStack
,从 Python 3.3 版开始:
In the rare case that you want to open a variable number of files all at the same time, you can use contextlib.ExitStack
, starting from Python version 3.3:
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"
大多数情况下,您有一组可变的文件,但您可能希望一个接一个地打开它们.
Most of the time you have a variable set of files, you likely want to open them one after the other, though.
这篇关于如何使用“with open"打开多个文件?在 Python 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!