10

Normally, we would use this to read/write a file:

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

And to do read one file and output to another, can i do it with just one with?

I've been doing it as such:

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

Is there something like the following, (the follow code dont work though):

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

is there any benefit to using one with and not multiple with? is there some PEP where it discusses this?

2 Answers 2

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

It used to be necessary to use (the now deprecated) contextlib.nested, but as of Python2.7, with supports multiple context managers.

Sign up to request clarification or add additional context in comments.

3 Comments

is there any benefit to using one with and not multiple with? is there some PEP where it discusses this?
@alvas No real benefit I think, except it satisfies the "flat is better than nested" principle from "Zen of Python" (import this)
@alvas: It saves you one level of indentation, which is helpful when trying to abide by the 80 characters-per-line (PEP8) limit.
0

You could try writing your own class and use it with with syntax

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.