Working with binary files in Python

Preview




 

Working with binary file in Python

Python provides the pickle module to write and read data from binary files.  To work with the pickle module, we need to import it in our program using import statement as: import pickle

We can use dump( ) and load ( ) methods of pickle module to write and read from a binary file respectively.

Steps to work with a binary file:

1. Import pickle module

We need to write import statement at the start of program to import pickle module as:

import pickle

2. Open binary file in the required file mode (read mode or write mode).

After importing pickle module we need to open the data file in binary mode. We need to use alphabet “b” with file file opening mode to open a file in binary mode

Example1:

f1=open(“file1.txt”,”wb”)

**Above statement will creater a new file file1.txt in binary mode. w for write mode and b for binary mode.

Example2:

f2=open(“file2.txt”,”ab”)

**Above statement will open file named file2.txt in append as well as binary mode. a for append mode and b for binary mode.

Example2:

f3=open(“file2.txt”,”rb”)

**Above statement will open file named file2.txt in read as well as binary mode. r for read mode and b for binary mode.

3. Process binary file by writing\reading objects.

We can use pickle.dump()  method to write data into binary file and pickle.load() method to read data from binary mode.

4. Close the file.

f1.close( )

 




Lesson tags: binary file in python
Back to: Python Programming Tutorial