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?
We can also open several files at once within a single “with” statement. The following code shows how to use the “with” statement to open two files, read the contents of one file, and then write the contents of the first file out to the second file:
Using this approach, the file that you’re working with is automatically closed so that you don’t have to remember to use file.close (). The following examples show how to use with open in different scenarios. The following code shows how to use the “with” statement to read a file into Python and print the contents of the file:
To be able to use two open statements in one with expression Python 2.7, Python 3.1 or newer are required. It’s also possible to nest with open statements instead of using two open statements in the same line. We often work with text file, but what about binary files?
How to Open File in Python? Python comes with functions that enable creating, opening, closing, reading, and writing files built-in. Opening a file in Python is as simple as using the open () function that is available in every Python version. The function returns a "file object."
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With