File Handling
Opening and Closing Files
open() function, file modes, and proper cleanup
Interview: Essential — tests understanding of file I/O, resource management, and the with statement
File handling is a fundamental skill in Python. The open() function provides access to files on disk, and understanding modes, encoding, and proper cleanup is essential for robust applications. Always use the with statement to ensure files are closed properly, even when exceptions occur.
The open() Function
open(file, mode, encoding)— returns a file object- Mode:
'r'(read),'w'(write),'a'(append),'b'(binary) - Always specify encoding (
encoding='utf-8') for text files - Files must be closed with
close()or viawithstatement
Why with Statement?
The with statement is a context manager that guarantees close() is called when the block exits — even if an exception occurs. This prevents resource leaks and is considered the standard way to handle files in Python.
Common Pitfall
Opening files without with or explicit close() can lead to resource leaks. On Windows, unclosed files can prevent deletion. On Linux, you can run out of file descriptors.
Use Cases
Reading configuration files at application startup
Writing log files for application monitoring
Processing data files (CSV, JSON, XML)
Reading/writing user-uploaded files
Template file processing and report generation
Common Mistakes
Not using with statement — files stay open causing resource leaks
Not specifying encoding — may fail on non-ASCII characters on some systems
Opening for reading without handling FileNotFoundError
Using open() in write mode ('w') when you meant append ('a') — overwrites file!
Forgetting that file paths are relative to the current working directory