gpt4 book ai didi

python - Python 中的 "With"语句要处理多个文件

转载 作者:太空狗 更新时间:2023-10-29 21:17:55 25 4
gpt4 key购买 nike

我如何使用 with这种情况下的声明?

f_spam = open(spam,'r')
f_bar = open(eggs,'r')
...
do something with these files
...
f_spam.close()
f_bar.close()

文件数量可以大于两个。

最佳答案

您还可以:

from contextlib import nested

with nested(open(spam), open(eggs)) as (f_spam, f_eggs):
# do something

在 Python 2.7 和 3.1+ 中,您不需要 nested 函数,因为 with 支持以下语法:

with open(spam) as f_spam, open(eggs) as f_eggs:
# do something

关于python - Python 中的 "With"语句要处理多个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2847939/

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