通常,我们会使用以下方法来读/写文件:
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 讨论了这个问题?
import this
)的“扁平比嵌套好”的原则。 - mdeous