Sometimes, you need to work with more than one file or resource at the same time. Handling multiple resources safely helps avoid mistakes and keeps your program clean.
Handling multiple resources in Python
Start learning this pattern below
Jump into concepts and practice - no test required
or
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Introduction
Syntax
Python
with open('file1.txt') as file1, open('file2.txt') as file2: # work with file1 and file2 here
You can open multiple resources in one with statement separated by commas.
All resources will be closed automatically when the block ends.
Examples
input.txt and writes it in uppercase to output.txt.Python
with open('input.txt') as infile, open('output.txt', 'w') as outfile: data = infile.read() outfile.write(data.upper())
Python
with open('file1.txt') as f1, open('file2.txt') as f2: lines1 = f1.readlines() lines2 = f2.readlines()
Sample Program
This program first creates two files with numbers. Then it opens both files at the same time, reads the numbers, and prints their sums.
Python
with open('numbers1.txt', 'w') as f1, open('numbers2.txt', 'w') as f2: f1.write('1\n2\n3\n') f2.write('4\n5\n6\n') with open('numbers1.txt') as file1, open('numbers2.txt') as file2: nums1 = [int(line.strip()) for line in file1] nums2 = [int(line.strip()) for line in file2] print('Sum of numbers1:', sum(nums1)) print('Sum of numbers2:', sum(nums2))
Important Notes
Using with for multiple resources keeps your code clean and safe.
If one resource fails to open, none will stay open accidentally.
You can use this pattern for files, network connections, or any resource that supports context management.
Summary
Use a single with statement to handle multiple resources together.
This ensures all resources close properly even if errors happen.
It makes your code easier to read and safer.
Practice
1. What is the main benefit of using a single
with statement to handle multiple resources in Python?easy
Solution
Step 1: Understand resource management with
Thewithwithstatement automatically closes resources like files when done, even if errors happen.Step 2: Benefits of handling multiple resources together
Using onewithfor many resources ensures all close properly, avoiding resource leaks.Final Answer:
It ensures all resources are properly closed even if an error occurs. -> Option DQuick Check:
Proper resource closing = A [OK]
Hint: One
with closes all resources safely [OK]Common Mistakes:
- Thinking it speeds up the program
- Believing resources stay open longer
- Assuming files get deleted automatically
2. Which of the following is the correct syntax to open two files together using a single
with statement?easy
Solution
Step 1: Recall correct
Multiple resources are separated by commas inside onewithsyntax for multiple resourceswithstatement, each with its ownasclause.Step 2: Check each option
with open('file1.txt') as f1, open('file2.txt') as f2: uses commas correctly and assigns each file to a separate variable. Others use wrong separators or combine incorrectly.Final Answer:
with open('file1.txt') as f1, open('file2.txt') as f2: -> Option CQuick Check:
Comma separates resources inwith[OK]
Hint: Use commas, not semicolons, to separate resources in
with [OK]Common Mistakes:
- Using semicolons instead of commas
- Trying to combine
asfor both files - Using 'and' instead of commas
3. What will be the output of this code snippet?
with open('file1.txt', 'w') as f1, open('file2.txt', 'w') as f2:
f1.write('Hello')
f2.write('World')
print(f1.closed, f2.closed)medium
Solution
Step 1: Understand
Files opened insidewithblock behaviorwithare automatically closed when the block ends.Step 2: Check
Since the print is outside theprint(f1.closed, f2.closed)after blockwith, both files are closed, so bothf1.closedandf2.closedare True.Final Answer:
True True -> Option AQuick Check:
Files closed afterwithblock = True True [OK]
Hint: Files close automatically after
with ends [OK]Common Mistakes:
- Thinking files stay open after
with - Confusing
closedattribute values - Assuming only one file closes
4. Identify the error in this code:
with open('file1.txt') as f1, open('file2.txt') as f2
data1 = f1.read()
data2 = f2.read()medium
Solution
Step 1: Check
Thewithstatement syntaxwithstatement must end with a colon (:). This code misses it.Step 2: Validate other parts
Opening two files in onewithis allowed, variables are defined by assignment, and reading files in default mode is valid.Final Answer:
Missing colon at the end of thewithstatement. -> Option AQuick Check:
Colon required afterwithheader [OK]
Hint: Always end
with lines with a colon [:] [OK]Common Mistakes:
- Forgetting the colon at the end
- Thinking multiple files can't be opened together
- Confusing read/write modes
5. You want to copy contents from
source.txt to dest.txt safely, ensuring both files close properly even if an error occurs. Which code correctly uses a single with statement to handle both files?hard
Solution
Step 1: Understand safe resource handling
Using a singlewithstatement with multiple resources ensures all files close properly even if errors happen.Step 2: Evaluate options
with open('source.txt') as src, open('dest.txt', 'w') as dst: dst.write(src.read()) uses onewithwith two files separated by a comma, correctly handling both. src = open('source.txt') dst = open('dest.txt', 'w') dst.write(src.read()) src.close() dst.close() manually closes files (less safe). with open('source.txt') as src: with open('dest.txt', 'w') as dst: dst.write(src.read()) uses nestedwith(correct but not singlewith). with open('source.txt') as src and open('dest.txt', 'w') as dst: dst.write(src.read()) uses invalid syntax with 'and'.Final Answer:
with open('source.txt') as src, open('dest.txt', 'w') as dst: dst.write(src.read()) -> Option BQuick Check:
Singlewithwith commas = D [OK]
Hint: Use commas inside one
with to open multiple files [OK]Common Mistakes:
- Using nested
withinstead of single - Forgetting to close files manually
- Using invalid syntax like 'and' in
with
