₹2,000.00 ₹300.00
The Python Programming Language at Champak's World
  • 22 students
  • 41 lessons
  • 0 quizzes
  • 10 week duration


Pickle in Python

In this short post we shall present a simple example where a list is written(serialized) into a file and then read back. Serialization and Deserialization is done via the Pickle package. In Pickle serialization is called pickling and deserialization is called unpickling. To use Pickle in a program you need to import it.

import pickle as p

To write or read from a file we need to open the file. This is done via the open function in python.
The syntax is.
f= open(full_file_path_with_name,file_access_mode).
Readers will recognize that this is a direct derivation from the C fopen function.
The options for file_access_mode are.
r = Opens file for reading in text mode. Sets pointer at the beginning of the file and this is the default mode.
rb = Opens file for reading in binary format.
r+ = Opens file for reading and writing.
rb+ = Opens file for reading and writing in binary format.
All read methods will throw an exception if file does not exist
w = Opens file for writing in text mode. Will erase all contents of the file if it exists. Create a new file if it doesn’t exist. Throw an exception if the path doesn’t exist.
wb = Opens file for writing in binary format.
w+ = Opens file for writing and reading in text format.
wb+ = Opens file for writing and reading in binary format.
a = Opens a file for appending in text mode.This means that new data is added to the end of the file if it exists. if the file doesn’t exist then a new file is created. Appending is equivalent to writing if file does not exist.
ab = Append in binary mode
ab+ = Append and read in binary mode.
Simple program to write a list into a file.
First of all import pickle and create a list.

import pickle as p


f=open("E:/data/list.txt", "wb")

The full_file_path_with_name is “E:/data/list.txt”.
The file_access_mode is “wb”=writebinary. The dump function in Python writes the object to the file stream. The flush method of the file object transfers all data to the stream(in this case the file). The close method writes EOF(End of File) and sets f to None(null).
For reading we shall use the following code.

import pickle as p
f=open("E:/data/list.txt", "rb")

Leave a Reply

Your email address will not be published. Required fields are marked *