'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 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1