gpt4 book ai didi

python - 使用 with - python 打开超过 1 个文件

转载 作者:太空狗 更新时间:2023-10-29 18:30:39 32 4
gpt4 key购买 nike

通常,我们会用它来读/写文件:

with open(infile,'r') as fin:
pass
with open(outfile,'w') as fout:
pass

要读取一个文件并输出到另一个文件,我可以只用一个 with 来完成吗?

我一直这样做:

with open(outfile,'w') as fout:
with open(infile,'r') as fin:
fout.write(fin.read())

有没有像下面这样的东西,(虽然下面的代码不起作用):

with open(infile,'r'), open(outfile,'w') as fin, fout:
fout.write(fin.read())

使用一个 with 而不是多个 with 有什么好处吗?是否有一些 PEP 讨论了这个问题?

最佳答案

with open(infile,'r') as fin, open(outfile,'w') as fout:
fout.write(fin.read())

以前必须使用(现已弃用)contextlib.nested , 但从 Python2.7 开始,with supports multiple context managers .

关于python - 使用 with - python 打开超过 1 个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20813944/

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