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:


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.


Excited to dive deeper into the world of Python programming? Look no further than my latest ebook, "Python Tricks - A Collection of Tips and Techniques".

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)

Tagged in: