Search code examples
pythonwith-statement

Python - How to replace multiple `with` statement blocks by a single `with` statement block


Consider the following piece of Python code:

with open('reviews.txt', 'r') as f:
    reviews = f.read()
with open('labels.txt', 'r') as f:
    labels = f.read()

The goal is to replace the two with statements with a single with statement.

How can this be achieved?


Solution

  • You can combine multiple open commands if you separate them by comma:

    with open('reviews.txt', 'r') as f1, open('labels.txt', 'r') as f2:
        reviews = f1.read()
        labels = f2.read()