Binary File Operations
If we wish to write a structure such as list or dictionary to a file and read it subsequently. We need to use the Python module pickle. Picking refers to the process of converting structure to a byte stream before writing to the file. While reading the contents of the file a reverse process called Unpickling is used to convert the byte stream back to the original structure.
We know that the methods provided in python for writing/reading a file work with string parameter. So when we want to work on a binary file, the conversion of data at the time of reading as well as writing is required.
“Pickle” method can be used to store any kind of object in a file as it allows us to store Python objects with their structures. So for storing data in binary format we will use “pickle” method.
First, we need to import the module. It provides two main methods for the purpose- dump and load.
For creation of a binary file we will use pickle.dump() to write object in the file, which is opened in binary access mode.
Syntax of dump() method:
Once data is stored in the file using dump(), then we can read the stored data using pickle.load() method.
Syntax of load() method:
We need to call load() each time dump() is called.
To create and write data of a list to a binary file
# to create and write data in a binary file import pickle #function definition def foperation(): list1=[10,20,30,40,100] f=open("data.dat","wb") pickle.dump(list1,f) print("Data written to Binary file") f.close() #function calling foperation()
Data written to Binary file
To read the contents from the above created binary.
# to read data from a binary file import pickle f=open("data.dat","rb") temp=pickle.load(f) f.close() print(temp)
[10, 20, 30, 40, 100]
To take input for names of students and further write them in a binary file.
import pickle #function definition def write_names(): lst= while True: n=input("Enter name ") lst.append(n) ch=input("Like to add more names ") if(ch=='y' or ch=='Y'): continue else: break fp=open("student","wb") pickle.dump(lst,fp) print("Names written in the file") fp.close() #function calling write_names()
Enter name Amit Like to add more names y Enter name Kapil Like to add more names y Enter name Mohit Like to add more names y Enter name Kishan Like to add more names n Names written in the file >>>