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
1). 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.
Syntax:
#writing_data_to_Binary_File import pickle pickle.dump(object,file)
Example 1:
#Example_writing_data_to_binary_file import pickle def write(): file = open("binary.dat",'wb') x = [1,2,3,4,5] #data we wrote in file pickle.dump(x,file) file.close() write()
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.