Write Data to Binary File in Python | File Handling in Python Programming

Write data to Binary File: Writing data to binary file is a way to perform write operation in our file. One thing is common everywhere, that is opening a file. Before performing any operation on file, opening and closing of file is mandatory for successful execution of task. There are two possibilities while writing data to a file ie.
(Note: .dat extension means binary file)


(i). If binary file abc.dat already existing and have some data written in the binary file and we are writing data to the same file abc.dat. Then in that case, the data written in the file is overridden with the new data.

(ii). If file is not existing in the system, then it will first create new file with the given name. And then perform the write operation. We can perform write operation on binary file using dump() method available in python pickle library.


Ways to write data to a binary file in Python
Using dump() function/method

(i). dump(): The method used for writing data to binary file is dump() method. It takes two arguments file object and file as parameters. It returns the object representation in byte mode. The dump() method belongs to pickle module.



import pickle


Example 1:


import pickle
def write():
    file = open("binary.dat",'wb')
    x = [1,2,3,4,5]    #data we wrote in file

Output data stored in our Binary File is:


Note: Hence we can observe the output that what data we wrote and what was inserted in our file. Actually data stored is correct but it has been stored in binary format which is not readable by humans.