【问题标题】:Open more than 1 file using with - python使用 with - python 打开多个文件
【发布时间】:2014-01-15 19:52:02
【问题描述】:

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

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

【问题讨论】:

    标签: python file-io with-statement


    【解决方案1】:
    with open(infile,'r') as fin, open(outfile,'w') as fout:
       fout.write(fin.read()) 
    

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

    【讨论】:

    • 使用一个with 而不是多个with 有什么好处吗?是否有一些 PEP 讨论这个?
    • @alvas 我认为没有真正的好处,除了它满足“Python之禅”中的“平面优于嵌套”原则(import this
    • @alvas:它为您节省了一级缩进,这在尝试遵守每行 80 个字符 (PEP8) 限制时很有帮助。
    【解决方案2】:

    您可以尝试编写自己的类并将其与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')
    

    【讨论】:

      猜你喜欢
      • 2011-06-04
      • 2020-03-16
      • 1970-01-01
      • 2021-06-07
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多