使用--python打开多个文件

时间:2013-12-28 11:22:21

标签: python file-io with-statement

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

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 个答案:

答案 0 :(得分:9)

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

曾经有必要使用(现已弃用)contextlib.nested,但从Python2.7开始,with supports multiple context managers

答案 1 :(得分: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')