gpt4 book ai didi

python - 如何在 Python 中使用 "with open"打开多个文件?

转载 作者:IT老高 更新时间:2023-10-28 12:00:56 24 4
gpt4 key购买 nike

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

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

最佳答案

从 Python 2.7(或分别为 3.1)开始,您可以编写

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

(历史记录:在早期版本的 Python 中,有时可以使用 contextlib.nested()嵌套上下文管理器。但是,这不会像预期的那样打开多个文件——有关详细信息,请参阅链接文档。)


在极少数情况下,您想同时打开不定数量的文件,您可以使用 contextlib.ExitStack ,从 Python 3.3 版开始:

with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# Do something with "files"

请注意,您通常希望按顺序处理文件,而不是同时打开所有文件,尤其是在文件数量可变的情况下:

for fname in filenames:
with open(fname) as f:
# Process f

关于python - 如何在 Python 中使用 "with open"打开多个文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4617034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com