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.
Pergunta
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?
Solução
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.
Outras dicas
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')