Reading and Writing Files in Python
Every program eventually needs to persist data beyond its runtime. Reading and writing files in Python is how you save results to disk and load them back later. This is essential for any real-world application—storing user settings, logging events, loading configuration files, or exporting data.
Python provides a simple interface for file operations through the built-in open() function and file objects. You can read and write text or binary data, and the same methods work across Windows, macOS, and Linux.
File Modes and Access
When you open a file, you specify a mode that determines what you can do. Python supports these mode characters, which can be combined:
| Character | Purpose |
|---|---|
'r' |
Read (default) |
'w' |
Write, truncating first |
'x' |
Exclusive create (fail if exists) |
'a' |
Append to end |
'+' |
Update (read and write) |
'b' |
Binary mode |
't' |
Text mode (default) |
Modes are combined by adding characters. For example, 'r+' means read and write an existing file, while 'w+' means write, truncate, and read. Text mode is the default. Add 'b' for binary.
An important note on encoding: when opening in text mode, specify encoding="utf-8" to avoid platform-dependent defaults.
Reading and Writing Files in Python
Let’s examine each mode with worked examples.
Read Mode (‘r’)
The 'r' mode (default) opens an existing file for reading. If the file doesn’t exist, it raises FileNotFoundError. Always use the with statement to ensure proper cleanup:
with open("sample1.txt", "r") as file1:
print(file1)
Output:
<_io.TextIOWrapper name='sample1.txt' mode='r' encoding='UTF-8'>
Read the entire file:
with open("sample1.txt", "r") as file1:
print(file1.read())
(sample1.txt contains: This is a sample.\n)
Output:
'This is a sample.\n'
Read a specific number of characters:
with open("sample1.txt", "r") as file1:
print(file1.read(10))
Output:
'This is a '
readline() reads the next line:
Notice that readline() reads the next line from where the cursor is, not always the first line:
with open("sample1.txt", "r") as file1:
print("readline: ", file1.readline(40))
print("read: ", file1.read(40))
(sample1.txt contains the same line repeated 5 times)
Output:
readline: 'This is a sample file.\n'
read: 'This is a sample file.\nThis is a sample '
After readline() reads the first line, the cursor moves to the second line. The next read() call continues from there.
readlines() returns a list of all lines:
with open("sample1.txt", "r") as file1:
print(file1.readlines())
Output:
['This is a sample file.\n', 'This is a sample file.\n', 'This is a sample file.\n', 'This is a sample file.\n', 'This is a sample file.\n']
Alternatively, loop over the file object directly (memory efficient for large files):
with open("sample1.txt", "r") as file1:
for line in file1:
print(line, end='')
Read and Write Mode (‘r+’)
The 'r+' mode opens an existing file for both reading and writing. It requires the file to already exist. The key thing to understand: write() doesn’t append to the end—it writes from the current cursor position and overwrites existing content.
with open("sample2.txt", "r+") as file1:
print("Before write: ", file1.read())
file1.write("Hello World!")
file1.seek(0)
print("After write: ", file1.read())
(sample2.txt initially contains: This is a sample.)
Output:
Before write: 'This is a sample.'
After write: 'This is a sample.Hello World!'
After read() consumes the entire file, the cursor is at the end. Then write() appends there. The seek(0) call moves the cursor back to the beginning so read() shows everything. Without seek(0), read() would return an empty string.
This is a quirk worth remembering: r+ writes where the cursor is, not necessarily at the end.
Write Mode (‘w’)
The 'w' mode opens a file for writing only. If the file exists, it truncates it (deletes all content). If it doesn’t exist, it creates it. You cannot read from a file opened in 'w' mode.
with open("sample1.txt", "r") as file1:
print("Before: ", file1.read())
with open("sample1.txt", "w") as file1:
file1.write("Hello World!")
with open("sample1.txt", "r") as file1:
print("After: ", file1.read())
(sample1.txt initially contained: This is a sample.\n)
Output:
Before: 'This is a sample.\n'
After: 'Hello World!'
Attempting to read in 'w' mode raises an error:
with open("sample1.txt", "w") as file1:
file1.write("Hello World!")
print(file1.read())
Python raises:
io.UnsupportedOperation: not readable
Write and Read Mode (‘w+’)
The 'w+' mode opens a file for writing and reading. Unlike 'r+', it creates the file if it doesn’t exist and truncates existing files.
Key differences:
'r+'requires the file to exist.'w+'creates it if it doesn’t'w+'truncates the file to zero length on open.'r+'never truncates, it just lets you seek and overwrite in place
with open("demo.txt", "w+") as file1:
file1.write("Hello World!")
file1.seek(0)
print(file1.read())
(demo.txt doesn’t exist initially)
Output:
'Hello World!'
The file is created and the content is written and read successfully.
Attempting the same with 'r+' raises an error:
with open("demo.txt", "r+") as file1:
file1.write("Hello World!")
file1.seek(0)
print(file1.read())
Python raises:
FileNotFoundError: [Errno 2] No such file or directory: 'demo.txt'
'w+' overwrites existing files:
with open("demo.txt", "w+") as file1:
file1.write("Say Hi")
file1.seek(0)
print(file1.read())
(demo.txt already contains Hello World!)
Output:
'Say Hi'
Append Mode (‘a’)
The 'a' mode opens a file for appending—the cursor always starts at the end, regardless of prior operations. Like 'w', you cannot read in pure append mode. It creates the file if it doesn’t exist.
with open("sample1.txt", "r") as file1:
print("Before: ", file1.read())
with open("sample1.txt", "a") as file1:
file1.write("Hello World!")
with open("sample1.txt", "r") as file1:
print("After: ", file1.read())
(sample1.txt initially contained: This is a sample.\n)
Output:
Before: 'This is a sample.\n'
After: 'This is a sample.\nHello World!'
Appending adds to the end without truncating. Attempting to read in 'a' mode raises an error:
with open("sample1.txt", "a") as file1:
file1.write("Hello World!")
print(file1.read())
Python raises:
io.UnsupportedOperation: not readable
Append and Read Mode (‘a+’)
The 'a+' mode appends to a file but also allows reading. Like 'a', writes always go to the end. To read the file, use seek(0) to move the cursor to the beginning.
with open("sample1.txt", "a+") as file1:
file1.seek(0)
print("Before: ", file1.read())
file1.write("Hello World!")
file1.seek(0)
print("After: ", file1.read())
(sample1.txt initially contained: This is a sample.\n)
Output:
Before: 'This is a sample.\n'
After: 'This is a sample.\nHello World!'
Best Practices
Always use the with statement. This is the most important rule. It automatically closes the file and ensures data is flushed to disk, even if an exception occurs:
# Good
with open("file.txt", "r", encoding="utf-8") as f:
data = f.read()
# Avoid (file may not flush properly)
f = open("file.txt", "r")
data = f.read()
f.close()
Specify encoding explicitly. The default encoding is platform-dependent (Windows uses cp-1252, Linux uses utf-8). For portability, always specify encoding="utf-8":
with open("file.txt", "r", encoding="utf-8") as f:
data = f.read()
Understand mode combinations. Each mode character means something:
'r'reads an existing file.'w'writes and truncates'a'appends.'x'creates exclusively'+'allows both reading and writing'b'means binary (for images, videos, and the like).'t'means text (default)
For detailed documentation and advanced options like buffering and newline handling, refer to the official Python file I/O documentation.
Conclusion
Reading and writing files is fundamental to any real program. Master the modes (r, w, a, r+, w+, a+) and always use with statements. Once you’re comfortable with file I/O, JSON with Python shows you how to store structured data that’s easy to parse.
What’s the most common file format you read from or write to in your projects?