How to close all the opened files using Python?

In Python, file-handling tasks like opening, reading, writing, and closing files are common operations. While opening files has its significance, it's equally important that files are closed properly to release system resources and maintain data integrity. This article explores different methods to close multiple opened files in Python.

Using Context Manager (Recommended)

Context managers are the most Pythonic way to handle file operations. The with statement automatically manages setup and teardown operations, ensuring files are closed even if exceptions occur.

Example

Here's how to open and automatically close multiple files using context managers ?

# Create sample files first
with open('file1.txt', 'w') as f:
    f.write("Content for file 1")
with open('file2.txt', 'w') as f:
    f.write("Content for file 2")

# Now open both files together
with open('file1.txt', 'r') as file1, open('file2.txt', 'r') as file2:
    content1 = file1.read()
    content2 = file2.read()
    print("File 1:", content1)
    print("File 2:", content2)

# Files are automatically closed outside the 'with' block
print("Files closed automatically")
File 1: Content for file 1
File 2: Content for file 2
Files closed automatically

Closing Multiple Files Manually

You can explicitly close files using the close() method, though this approach is more error-prone than context managers.

Example

# Create sample files
with open('file1.txt', 'w') as f:
    f.write("Sample content 1")
with open('file2.txt', 'w') as f:
    f.write("Sample content 2")

# Open files manually
file1 = open('file1.txt', 'r')
file2 = open('file2.txt', 'r')

# Perform operations
print("File 1 content:", file1.read())
print("File 2 content:", file2.read())

# Close files manually
file1.close()
file2.close()

print("Files closed manually")
File 1 content: Sample content 1
File 2 content: Sample content 2
Files closed manually

Using a List of File Objects

When dealing with multiple files, you can store file objects in a list and close them all at once.

Example

# Create sample files
for i in range(1, 4):
    with open(f'file{i}.txt', 'w') as f:
        f.write(f"Content for file {i}")

# Open multiple files and store in a list
file_objects = [
    open('file1.txt', 'r'),
    open('file2.txt', 'r'), 
    open('file3.txt', 'r')
]

# Perform operations
for i, file_obj in enumerate(file_objects, 1):
    print(f"File {i} content:", file_obj.read())

# Close all files
for file_obj in file_objects:
    file_obj.close()

print("All files closed")
File 1 content: Content for file 1
File 2 content: Content for file 2
File 3 content: Content for file 3
All files closed

Using try-finally Block

The try-finally block ensures files are closed even if exceptions occur during file operations.

Example

# Create sample files
with open('file1.txt', 'w') as f:
    f.write("Data in file 1")
with open('file2.txt', 'w') as f:
    f.write("Data in file 2")

file1 = None
file2 = None

try:
    file1 = open('file1.txt', 'r')
    file2 = open('file2.txt', 'r')
    
    # Perform operations
    print("File 1:", file1.read())
    print("File 2:", file2.read())
    
finally:
    # Close files regardless of what happens
    if file1:
        file1.close()
    if file2:
        file2.close()
    print("Files closed in finally block")
File 1: Data in file 1
File 2: Data in file 2
Files closed in finally block

Using contextlib.closing

The contextlib.closing function wraps file objects to ensure proper closure when used as context managers.

Example

import contextlib

# Create sample files
with open('file1.txt', 'w') as f:
    f.write("Content 1")
with open('file2.txt', 'w') as f:
    f.write("Content 2")

# Use contextlib.closing
with contextlib.closing(open('file1.txt', 'r')) as file1, \
     contextlib.closing(open('file2.txt', 'r')) as file2:
    
    print("File 1:", file1.read())
    print("File 2:", file2.read())

print("Files automatically closed with contextlib.closing")
File 1: Content 1
File 2: Content 2
Files automatically closed with contextlib.closing

Comparison of Methods

Method Automatic Cleanup Exception Safe Readability
Context Manager Yes Yes Excellent
Manual close() No No Good
try-finally Yes Yes Fair
contextlib.closing Yes Yes Good

Conclusion

Always use context managers with the with statement for file operations as they automatically handle file closure and are exception-safe. For multiple files, either open them together in a single with statement or use try-finally blocks when manual control is needed.

Updated on: 2026-03-24T18:08:41+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements