Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open more than 1 file using with - python

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?

like image 302
alvas Avatar asked Dec 28 '13 11:12

alvas


People also ask

How do I open multiple files at once in Python?

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:

What does “with open” mean in Python?

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:

How to use two open statements in one expression in Python?

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 a file in Python?

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."


1 Answers

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.

like image 190
unutbu Avatar answered Nov 15 '22 19:11

unutbu