0

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?

4
  • Please elaborate on "combine the two different file openings". It's a bit vague. Commented Nov 11, 2017 at 23:06
  • Why do you want to combine them? Just to make your code shorter? Are you expecting any other advantage? Commented Nov 11, 2017 at 23:08
  • The advantage is more mental in that a single with statement corresponds to the thought 'get the reviews and labels'. Commented Nov 11, 2017 at 23:21
  • @BryanOakley Terry's comment summarises my motivation. It makes the code cleaner, succinct and easier to grasp. Commented Nov 11, 2017 at 23:27

1 Answer 1

2

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.