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.
0
0
Handling multiple resources in Python
Introduction
When you want to read from one file and write to another at the same time.
When you need to open several files to compare their contents.
When you want to manage multiple network connections or database connections safely.
When you want to make sure all resources close properly even if an error happens.
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
This reads text from
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())
This opens two files and reads all lines from both.
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))
OutputSuccess
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.