Back to course

File Handling 2: The `with` Statement (Context Managers)

Python Programming: The 0 to Hero Bootcamp

The with Statement

Manually calling file.close() can be easily forgotten, especially if an exception occurs during file processing. The with statement (using context managers) guarantees that the file is automatically closed, even if errors occur.

Syntax

python with open(filename, mode) as file_object: # Work with the file_object ...

File is automatically closed when indentation ends

Example: Safe Reading

Assume data/users.txt exists.

python file_path = 'data/users.txt' user_list = []

try: with open(file_path, 'r') as f: for line in f: user_list.append(line.strip())

print("Users loaded successfully.")
print(user_list)

except FileNotFoundError: print(f"Error: File not found at {file_path}")

Best Practice: Always use the with open(...) construct for file I/O.