In this blog series, we'll explore how to handle files in Python, starting from the basics and gradually progressing to more advanced techniques.
By the end of this series, you'll have a strong understanding of file operations in Python, enabling you to efficiently manage and manipulate data stored in files.
The series will consist of five posts, each building on the knowledge from the previous one:
- Introduction to File Handling in Python: Reading and Writing Files
- (This Post) Working with Different File Modes and File Types
- Handling Large Files and File Operations in Python
- Using Context Managers and Exception Handling for Robust File Operations
- Advanced File Operations: Working with CSV, JSON, and Binary Files
In our last post, we talked about the basics of how to handle files in Python.
We covered how to open, read, write, and close files.
Now, we'll look more closely at different file modes and learn how to work with both text and binary files.
Knowing about these different file modes will help you handle different types of files and do more advanced things with them.
Summary of File Modes
When you work with files in Python, the open()
function lets you choose how you want to open the file using different modes.
These modes tell Python if you want to read, write, add more data, or work with binary data.
Here’s a quick summary of the common file modes:
'r'
: Read - Open the file so you can read it (this is the default mode). The file must already exist, or you'll get an error.'w'
: Write - Open the file so you can write to it. If the file already exists, its contents will be erased. If the file doesn’t exist, a new one will be created.'a'
: Append - Open the file so you can write to it but keep the existing content. New data is added at the end of the file.'r+'
: Read and Write - Open the file so you can both read and write to it. The file must already exist.'w+'
: Write and Read - Open the file so you can both write and read from it. If the file exists, it will be cleared. If it doesn’t exist, a new one will be created.
Besides these basic modes, Python also has modes for handling binary data, which we’ll talk about later in this post.
Get the eBook
Inside, you'll discover a plethora of Python secrets that will guide you through a journey of learning how to write cleaner, faster, and more Pythonic code. Whether it's mastering data structures, understanding the nuances of object-oriented programming, or uncovering Python's hidden features, this ebook has something for everyone.
Working with Text Files
Text files store data as plain text, and Python makes it easy to read from and write to these files using simple string operations.
Let’s look at some examples to understand how different file modes affect how we work with text files.
Example: Writing to a Text File ('w'
Mode)
# Open a file in write mode
with open('example.txt', 'w') as file:
# Write multiple lines to the file
file.write("Hello, Python!\n")
file.write("This is a text file.\n")
In this example, we open a file called example.txt
in write mode ('w'
).
If the file already exists, its content will be overwritten.
We then write two lines of text to the file.
Using the with
statement ensures the file is automatically closed once the operations are complete.
Example: Appending to a Text File ('a'
Mode)
# Open the file in append mode
with open('example.txt', 'a') as file:
# Add another line at the end of the file
file.write("This line is appended to the file.\n")
Here, we use the append mode ('a'
) to add a new line to the file without overwriting the existing content.
This mode is useful when you need to keep previous data intact.
Example: Reading from a Text File ('r'
Mode)
# Open the file in read mode
with open('example.txt', 'r') as file:
# Read and print each line from the file
for line in file:
print(line.strip()) # strip() removes the newline characters
In this example, we open the file in read mode ('r'
) and use a loop to print each line.
The strip()
method is used to remove the newline characters at the end of each line.
Working with Binary Files
Binary files store data in a format that isn't readable by humans and is usually interpreted by specific applications or systems.
Examples of binary files include images, videos, and executable files.
When working with binary files in Python, you need to use binary modes:
'rb'
: Read Binary - Opens the file for reading in binary mode.'wb'
: Write Binary - Opens the file for writing in binary mode.'ab'
: Append Binary - Opens the file for adding data in binary mode.
Example: Reading a Binary File ('rb'
Mode)
# Open a binary file (e.g., an image) in read binary mode
with open('image.png', 'rb') as file:
# Read the binary content
binary_data = file.read()
# Print the first 10 bytes of the binary data
print(binary_data[:10])
In this example, we open an image file in read binary mode ('rb'
).
We then read the entire file content as binary data and print the first 10 bytes.
This is a useful technique for handling non-text data, such as images, audio files, or any other binary file format.
Example: Writing to a Binary File ('wb'
Mode)
# Open a new binary file in write binary mode
with open('output.bin', 'wb') as file:
# Write some binary data to the file
file.write(b'\x00\xFF\xFE\xFA')
Here, we open a new binary file in write binary mode ('wb'
) and write a sequence of bytes to it.
The b
before the string indicates that the data is in bytes, not text.
Combining Read and Write Operations
Sometimes, you might want to open a file to both read from and write to it.
Python has modes like 'r+'
, 'w+'
, and 'a+'
to handle these situations.
These modes let you read and write to a file without having to close and reopen it.
Example: Reading and Writing with 'r+'
Mode
# Open the file in read/write mode
with open('example.txt', 'r+') as file:
# Read the current content
content = file.read()
# Move the cursor to the beginning of the file
file.seek(0)
# Write new content
file.write("Updated text at the beginning.\n")
In this example, we open a text file in 'r+'
mode, which allows us to read the file and then write new content.
The seek(0)
function moves the cursor back to the beginning of the file so that we can overwrite the initial content.
Handling Different Encodings in Text Files
By default, Python uses the system's default encoding (often UTF-8) when reading and writing text files.
However, you might need to work with files that use different encodings. To handle this, you can specify the encoding when you open a file.
Example: Reading a File with a Specific Encoding
# Open the file with a specific encoding (e.g., UTF-16)
with open('example_utf16.txt', 'r', encoding='utf-16') as file:
content = file.read()
print(content)
In this example, we open a text file that is encoded in UTF-16 by specifying the encoding
argument.
This ensures that Python correctly interprets the file's content.
Conclusion and Next Steps
In this post, we looked at different file modes in Python and learned how to work with both text and binary files.
We also saw how to combine reading and writing operations using modes like 'r+'
and how to handle different file encodings.
In the next post, we’ll explore how to handle large files efficiently and optimize file operations for better performance.
Stay tuned as we continue to expand our understanding of file handling in Python!
If you would like this post, learn from it, and would like to support my work, consider leaving a small donation:
If you are not a Premium Django Series Subscriber, sign up below and get a 25% discount on the yearly membership:
Feel free to use the feedback buttons or send in a comment for future content you would love to see or what new things you learned from this post.
Also, share it with a friend who would love to read it.