使用Python中的“with”打开多个文件

10

通常,我们会使用以下方法来读/写文件:

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 讨论了这个问题?

2个回答

9

使用一个with语句和多个with语句有什么好处?是否有PEP文档讨论了这个问题? - alvas
2
@alvas 我认为它没有实际好处,除了满足来自“Python之禅”(import this)的“扁平比嵌套好”的原则。 - mdeous
@alvas:这可以帮助你节省一级缩进,当你试图遵守每行80个字符(PEP8)的限制时非常有用。 - unutbu

0
你可以尝试编写自己的类,并使用with语法。
class open_2(object):
    def __init__(self, file_1, file_2):
        self.fp1 = None
        self.fp2 = None
        self.file_1 = file_1
        self.file_2 = file_2

    def __enter__(self):
        self.fp1 = open(self.file_1[0], self.file_1[1])
        self.fp2 = open(self.file_2[0], self.file_2[1])
        return self.fp1, self.fp2

    def __exit__(self, type, value, traceback):
        self.fp1.close()
        self.fp2.close()

with open_2(('a.txt', 'w'), ('b.txt', 'w')) as fp:
    file1, file2 = fp

    file1.write('aaaa')
    file2.write('bbb')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接