Python Binary Files

Binary files handle data in the form of bytes. Hence, they can be used to read or write text, images or audio and video files.

Open binary file

To open a binary file for reading purpose, we can use 'rb' mode. Here, 'b' is attached to 'r' to represent that it is a binary file.

Write binary file

Similarly to write bytes into a binary file, we can use 'wb' mode. To read bytes from a binary file, we can use the read() method and to write bytes into a binary file, we can use the write() methods.

Binary file examples:

Let's write a program where we want to open an image file like .jpg, .gif or .png file and read bytes from that file. These bytes are then written into a new binary file. It means we are copying an image file as another file.

Following example will copy an image file into another file.

CopiedCopy Code

#copying an image into a file
#open the files in binary mode 
f1 = open('cat.jpg', 'rb') 
f2 = open('new.jpg', 'wb') 
#read bytes from f1 and write into f2 
bytes = f1.read() 
f2.write(bytes) 
#close the files 
f1.close()