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 in Python:
1. Import pickle module
We need to write import statement at the start of program to import pickle module as:
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
**Above statement will creater a new file file1.txt in binary mode. w for write mode and b for binary mode.
**Above statement will open file named file2.txt in append as well as binary mode. a for append mode and b for binary mode.
**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.
Click here for Quiz on Functions in Python
Popular Books of Computer Science