The Wayback Machine - https://web.archive.org/web/20240712114355/https://www.geeksforgeeks.org/append-data-to-binary-file-in-python/
Open In App

Append Data To Binary File In Python

Last Updated : 29 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We are given a binary file and our task is to append data into that binary file in Python using different approaches. In this article, we will see how we can append data to binary file in Python.

Append Data to Binary File in Python

below, are the examples of Append Data To Binary File In Python:

  • Appending String Datatype
  • Append List of Integers
  • Append Data from Another binary File

Appending String Datatype To Binary File In Python Programming

In this example, below code opens the binary file ‘binary_file.bin’ in append mode, allowing new data to be added without overwriting existing content. It defines binary data ‘data’ to be appended and writes it to the file.

Python3




# Opening the created binary file in append mode
with open('binary_file.bin', 'ab') as file:
    # Data to append
    data = b'New data to append\n'
 
    # Writing the data to the file
    file.write(data)
 
print("Data has been appended to the binary file.")


Output

Data has been appended to the binary file.
Screenshot-(26)

Appending a String to the binary file

Append List of Integers To Binary File In Python Programming

In this example, below code appends a list of integers [1, 2, 3, 4, 5] to the binary file ‘binary_file.bin’. Inside the loop, each integer is converted to a 4-byte big-endian representation using to_bytes method, and then these byte sequences are written to the file.

Python3




data = [1, 2, 3, 4, 5]
 
# Opening the same binary file in append mode
with open('binary_file.bin', 'ab') as file:
    # Converting integers to bytes and append to the file
    for num in data:
        file.write(num.to_bytes(4, byteorder='big'))


Output

Screenshot-(27)

integers appended from a list to a binary file

Append Data from Another Binary File In Python Programming

Step 1: Create New File code

below code creates a new binary file ‘another_binary_file.bin’ and writes the sample data, which is a byte-encoded string containing the message “Hello, this is another binary file!”. The file is opened in binary write mode (‘wb’) to ensure proper handling of binary data.

Python3




# Creating another binary file
with open('another_binary_file.bin', 'wb') as file:
    # Sample data
    data = b'\nHello, this is another binary file!\n'
 
    # Writing the data to the file
    file.write(data)


Output

Screenshot-(28)

New binary file created

Screenshot-(29)

Inside the new binary file

Step 2: Append Data to Binary File

Below code reads the contents of the binary file ‘another_binary_file.bin‘ into the variable `binary_data` using binary read mode (‘rb‘). It then appends this binary data to the original binary file ‘binary_file.bin‘ in append mode (‘ab’). This allows the data from one binary file to be saved and appended to another.

Python3




# Saving the data from one binary file
with open('another_binary_file.bin', 'rb') as source_file:
    binary_data = source_file.read()
 
# Writing the data of the previous file in the original file
with open('binary_file.bin', 'ab') as destination_file:
    destination_file.write(binary_data)


Output

Screenshot-(30)

Data added from the new file to the original file

Conclusion

In conclusion , Appending data to a binary file in Python is a useful operation when working with non-textual data or complex data structures. The ability to efficiently add new data while preserving the existing structure makes binary files a preferred choice for various applications. Understanding the syntax and advantages of appending data to binary files empowers developers to handle diverse data storage scenarios in their Python projects.



Similar Reads

How To Append Data To Yaml File Using Python
We are given a YAML file and our task is to append data inside that YAML file by using different approaches in Python. In this article, we will see how we can append data to YAML file using Python. We have data.yml file containing the following data and we will append the data inside this file. data.yaml GeeksforGeeks: EducationAppend Data To Yaml
3 min read
Python append to a file
While reading or writing to a file, access mode governs the type of operations possible in the opened file. It refers to how the file will be used once it's opened. These modes also define the location of the File Handle in the file. The definition of these access modes is as follows: Append Only (‘a’): Open the file for writing.Append and Read (‘a
4 min read
Python - Append content of one text file to another
Having two file names entered by users, the task is to append the content of the second file to the content of the first file with Python. Append the content of one text file to anotherUsing file objectUsing shutil moduleUsing fileinput moduleSuppose the text files file1.txt and file2.txt contain the following data. file1.txt file2.txt Append the c
3 min read
Append to JSON file using Python
The full form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called JSON. To use this feature, we import the JSON package in Python script. The text in JSON is done through quoted-
2 min read
Append Text or Lines to a File in Python
Appending text or lines to a file is a common operation in programming, especially when you want to add new information to an existing file without overwriting its content. In Python, this task is made simple with built-in functions that allow you to open a file and append data to it. In this tutorial, we'll explore what it means to append text or
3 min read
How to append a new row to an existing csv file?
For writing a CSV file, the CSV module provides two different classes writer and Dictwriter. Here we will discuss 2 ways to perform this task effectively. The First will be 'append a list as a new row to the existing CSV file' and second way is 'Append a dictionary as a new row to the existing CSV file.' First, let's have a look at our existing CSV
3 min read
How to Append Pandas DataFrame to Existing CSV File?
In this discussion, we'll explore the process of appending a Pandas DataFrame to an existing CSV file using Python. Add Pandas DataFrame to an Existing CSV File. To achieve this, we can utilize the to_csv() function in Pandas with the 'a' parameter to write the DataFrame to the CSV file in append mode. Pandas DataFrame to_csv() Syntax Syntax : df.t
3 min read
How to append new data to existing XML using Python ElementTree
Extensible Markup Language (XML) is a widely used format for storing and transporting data. In Python, the ElementTree module provides a convenient way to work with XML data. When dealing with XML files, it is common to need to append new data to an existing XML document. This can be achieved efficiently using Python's ElementTree module. What is P
4 min read
How to Append Data in Excel Using Python
We are given an Excel file and our task is to append the data into this excel file using Python. In this article, we'll explore different approaches to append data to an Excel file using Python. Append Data in Excel Using PythonBelow, are some examples to understand how to append data in excel using Python: excel1.xlsx: Let's say we have an existin
2 min read
Append data to an empty Pandas DataFrame
Let us see how to append data to an empty Pandas DataFrame. Creating the Data Frame and assigning the columns to it # importing the module import pandas as pd # creating the DataFrame of int and float a = [[1, 1.2], [2, 1.4], [3, 1.5], [4, 1.8]] t = pd.DataFrame(a, columns =["A", "B"]) # displaying the DataFrame print(t) print(t
2 min read
Practice Tags :
three90RightbarBannerImg