Python File I/O: Opening, Reading, Writing, Modes, and Common Pitfalls
This article explains Python's file handling fundamentals, covering the open() function syntax, file object methods, various read/write modes, encoding options, pointer manipulation with seek() and tell(), and best practices to avoid data loss when reading or writing large files.
Files are an abstract concept for long‑term data storage, and Python provides the built‑in open() function for reading and writing them. The basic syntax is f = open(filename, mode) , where mode determines how the file is accessed.
The open() call returns a file object that supports methods such as read() , write() and close() . After performing operations you should always call close() (or flush() ) to ensure buffered data is written to disk.
Example of writing numbers 0‑9999 to a text file:
<code>fw = open('测试文件.txt', 'wt')
for i in range(10000):
fw.write('{} '.format(i))
fw.close()
</code>If close() is omitted, the last part of the data may be lost because Python buffers writes in memory and only flushes the buffer when the file is closed.
Common file opening modes are listed below:
Mode
Description
rRead‑only (default). Raises
FileNotFoundErrorif the file does not exist.
wWrite‑only, truncates existing file or creates a new one.
aAppend‑only, creates the file if it does not exist, otherwise writes at the end.
xExclusive creation, fails with
FileExistsErrorif the file already exists.
rbRead binary.
wbWrite binary, truncates or creates.
abAppend binary.
r+Read and write.
w+Read and write, truncates or creates.
a+Read and write, creates if needed, pointer at end.
rtRead text (default for text files).
wtWrite text, truncates or creates.
Python provides three primary file‑reading functions: read() , readline() , and readlines() . For large files it is more efficient to iterate line by line:
<code>fo = open(fname, 'rt')
for line in fo:
print(line)
fo.close()
</code>When dealing with different encodings, specify the encoding argument, e.g., open('test.txt', 'rt', encoding='utf-8') . The default on Windows is "GBK"; you can also use encoding='utf-8-sig' for files with a BOM.
After reading a file, the file pointer is at the end. Use seek(0) to rewind, or reopen the file. The tell() method reports the current byte offset.
<code>fo = open('test.txt', 'rt')
for line in fo:
line = line.replace('\n', '')
print(line)
fo.seek(0) # rewind to start
fo.close()
</code>If you provide only a filename, Python looks for the file in the current working directory. For files elsewhere, use an absolute path and escape backslashes (e.g., 'D:\\python\\testfile.txt' ).
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.