Python File I/O: Reading and Writing Files Safely
Learn how to read and write files in Python. Master open(), read(), write(), and context managers to handle file operations securely without resource leaks.
Overview
File Input/Output (I/O) is a fundamental capability that allows Python programs to interact with the persistent storage of a computer. Whether you are building a simple logger, reading configuration files, or processing massive data arrays, your program needs a reliable way to open, read, write, and close files on disk. Python provides clean, built-in functions to make file system interaction straightforward and cross-platform.
The primary tool for file access in Python is the built-in `open()` function. This function accepts a file path and a mode string. The mode determines how the file is accessed: `'r'` for reading, `'w'` for writing (which overwrites the file), `'a'` for appending content to the end, and `'b'` for binary mode (useful for images or serialized data). Crucially, whenever you open a file, it consumes an operating system handle. If you fail to close the file, you can cause memory leaks or file lock issues.
To guarantee that files are always closed properly, Python developers use the `with` statement, which implements a context manager. When using `with open(...) as file:`, Python automatically closes the file handle once the code block exits, even if an unexpected exception occurs inside. Reading data can be done line-by-line using `for line in file:` or all at once via `.read()`, `.readline()`, or `.readlines()`. Writing text is handled via `.write()` or `.writelines()`, enabling smooth, safe, and efficient file operations.
Code Example
Writing a greeting to a temporary text file and reading it back line by line using safe context managers.
filename = "sample.txt"
# Writing to a file
with open(filename, "w") as file:
file.write("Hello, Python coder!\n")
file.write("This is a line in a file.\n")
file.write("File I/O is simple.\n")
print("File written successfully.\n--- Reading File ---")
# Reading from a file line by line
with open(filename, "r") as file:
for index, line in enumerate(file, 1):
print(f"Line {index}: {line.strip()}")File written successfully.
--- Reading File ---
Line 1: Hello, Python coder!
Line 2: This is a line in a file.
Line 3: File I/O is simple.Real-world Use Cases
- Logging errors and program output
- Reading configuration files (e.g., .env or config.txt)
- Saving user reports or exported analytical summaries
Frequently Asked Questions
What is the difference between write and append modes?
Write mode ('w') truncates the file to zero length, deleting any existing content before writing. Append mode ('a') places the cursor at the end, adding new text without deleting existing contents.
Why should I use the with statement?
The with statement acts as a context manager, ensuring files are closed automatically, which prevents memory leaks and lock file errors.
Keep Learning
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
How to Read a File in Python
Learn how to read files in Python. Master the with open statement, readline, readlines, and safely handling file exceptions.
Python Dictionary Methods
Learn Python dictionary methods. Complete reference guide for key-value pair insertions, retrievals, updates, and checks.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.