DEV Community

Cover image for Working with Different File Modes and File Types in Python
Developer Service
Developer Service

Posted on • Updated on • Originally published at developer-service.blog

Working with Different File Modes and File Types in Python

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.


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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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])
Enter fullscreen mode Exit fullscreen mode

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')
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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)

Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)