Python File I/O: Reading and Writing Files
This article explains how Python interacts with the operating system to open, read, write, and close files using the built‑in open() function, various file modes, error handling, the with statement for automatic resource management, and considerations for binary data and character encodings.
File I/O is one of the most common operations; Python provides built‑in functions compatible with C for reading and writing files. The operating system manages disk access, so programs request a file object (file descriptor) via open() and then read from or write to it.
To open a file for reading, use open('path/to/file', 'r') . If the file does not exist, open() raises an IOError (or FileNotFoundError ) with an error code and message.
Once opened, f.read() reads the entire file into a str object. For large files, use read(size) to read a limited number of bytes, readline() to read one line, or readlines() to get a list of all lines.
Always close the file with f.close() to release OS resources. To guarantee closing even when errors occur, wrap the operations in a try ... finally block:
try:
f = open('/path/to/file', 'r')
print(f.read())
finally:
if f:
f.close()Python simplifies this with the with statement, which automatically calls close() :
with open('/path/to/file', 'r') as f:
print(f.read())When reading large files, prefer read(size) or iterate over lines to avoid loading the entire file into memory. For binary files (e.g., images, videos), open with mode 'rb' and read bytes.
To read files with non‑UTF‑8 encodings, pass the encoding argument to open(), e.g., open('gbk.txt', 'r', encoding='gbk') . If the file contains illegal byte sequences, handle them with the errors parameter, such as errors='ignore' .
Writing files mirrors reading: use open('path/to/file', 'w') for text or 'wb' for binary. Call f.write() to write data and f.close() to flush buffers; using with ensures safe closure.
To append to an existing file without overwriting, open it with mode 'a' (or 'ab' for binary). All mode definitions are detailed in Python's official documentation.
Summary : In Python, file reading and writing are performed via the open() function, with various modes and optional encoding parameters; the with statement is the recommended pattern for safe and concise file I/O.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.