Binary Files
Binary Files
BINARY FILES
o Binary file: basic operations on a binary file:
o Open using file open modes (rb, rb+,wb,wb+, ab, ab+),
o Close a binary file,
o import pickle module, dump() and load() method,
o read, write/create, search, append and update operations in a binary file.
Binary files store data in the binary format (0’s and 1’s) which is understandable
by the machine. So when we open the binary file in our machine, it decodes the
data and displays in a human-readable format.
There are three basic modes of a binary file:
The plus symbol followed by file mode is used to perform multiple operations
together. For example, rb+ is used for reading the opening file for reading and writing.
The cursor position isat the beginning when + symbol is written with file mode.
Binary File Modes: File mode governs the type of operations read/write/append
possible in theopened file. It refers to how the file will be used once its opened.
File Description
Mode
rb Read Only: Opens existing file for read operation
wb Write Only: Opens file for write operation. If file does not exist, file is created. Iffile exists, it
overwrites data.
ab Append: Opens file in write mode. If file exist, data will be appended at the end.
rb+ Read and Write: File should exist, Both read and write operations can beperformed.
wb+ Write and Read: File created if not exist, If file exist, file is truncated.
ab+ Write and Read: File created if does not exist, If file exist data is truncated.
Pickle Module: Python pickle is used to serialize and deserialize a python object structure.
Any object on python can be pickled so that it can be saved on disk.
Example:
import pickle
In this module,we shall discuss two functions of pickle module, which are:
i) dump():To store/write the object data to the file.
ii) load():To read the object data from a file and returns the object data.
Syntax:
Write the object to the file:
pickle.dump(objname, file-object )
pickle.load(file-object)
Page 3 of 4
Page 4 of 4