Fundamentals 8 min read

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.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python File I/O: Opening, Reading, Writing, Modes, and Common Pitfalls

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

r

Read‑only (default). Raises

FileNotFoundError

if the file does not exist.

w

Write‑only, truncates existing file or creates a new one.

a

Append‑only, creates the file if it does not exist, otherwise writes at the end.

x

Exclusive creation, fails with

FileExistsError

if the file already exists.

rb

Read binary.

wb

Write binary, truncates or creates.

ab

Append binary.

r+

Read and write.

w+

Read and write, truncates or creates.

a+

Read and write, creates if needed, pointer at end.

rt

Read text (default for text files).

wt

Write 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' ).

File write example
File write example
PythonencodingFile I/ORead Writeopen()file modes
Python Programming Learning Circle
Written by

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.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.