File Handling
File handling is a fundamental skill for any Python developer. Programs frequently need to read configuration files, process data from text files, log outp...
File Handling in Python: Opening, Reading, and Closing Files
File handling is a fundamental skill for any Python developer. Programs frequently need to read configuration files, process data from text files, log output, or save results. Python provides straightforward built-in tools for working with files on the local filesystem.
The primary function for working with files in Python is open(). It takes the file path as its first argument and a mode string as the second. The most common modes are "r" for reading, "w" for writing (which overwrites the file), "a" for appending, and "b" for binary mode, which can be combined with the others like "rb" or "wb".
The safest way to work with files is using the with statement, which automatically closes the file when the block exits, even if an exception occurs:
with open("data.txt", "r") as file: content = file.read() print(content)
The with statement eliminates the need to call file.close() manually and prevents resource leaks. This is the recommended approach in all modern Python code.
File objects have several useful methods. read() returns the entire file content as a string. readline() returns one line at a time. readlines() returns a list where each element is a line from the file, including the newline character at the end.
You can also iterate over a file object directly in a for loop, which reads one line per iteration without loading the entire file into memory. This is the most memory-efficient approach for large files:
with open("large_file.txt", "r") as file: for line in file: process(line.strip())
When opening files, you should specify the encoding explicitly to avoid issues on different operating systems. UTF-8 is the most common encoding and works well for most text files:
with open("notes.txt", "r", encoding="utf-8") as file: data = file.read()
File paths can be absolute (starting from the root of the filesystem) or relative (starting from the current working directory). Using relative paths makes code more portable, but absolute paths remove ambiguity.
Interview tip: Always mention the with statement when discussing file handling. Interviewers look for this because it demonstrates that you understand resource management. Forgetting to close a file can cause data loss or lock the file for other processes, especially on Windows systems.