Open In App

How to update a pickle file in Python?

Python pickle module is used for serializing and de-serializing a Python object structure. Any object in Python can be pickled so that it can be saved on a disk. What pickle does is that it “serializes” the object first before writing it to file. Pickling is a way to convert a python object (list, dict, etc.) into a character stream. The idea is that this character stream contains all the information necessary to reconstruct the object in another python script

Pickle serializes a single object at a time, and reads back a single object – the pickled data is recorded in sequence on the file. If you simply do pickle.load you would be reading the first object serialized into the file (not the last one as you’ve written). After unserializing the first object, the file-pointer is at the beginning of the next object – if you simply call pickle.load again, it will read that next object – do that until the end of the file



Functions Used:

Syntax:



pickle.load(file, *, fix_imports = True, encoding = “ASCII”, errors = “strict”)

Syntax:

pickle.dump(obj, file, protocol = None, *, fix_imports = True)

To start with, we first have to insert it into a pickle file. The implementation is given below:

Approach

Program:




# code
import pickle
print("GFG")
 
 
def write_file():
 
    f = open("travel.txt", "wb")
    op = 'y'
 
    while op == 'y':
 
        Travelcode = int(input("enter the travel id"))
        Place = input("Enter the Place")
        Travellers = int(input("Enter the number of travellers"))
        buses = int(input("Enter the number of buses"))
 
        pickle.dump([Travelcode, Place, Travellers, buses], f)
 
        op = input("Dp you want to continue> (y or n)")
 
    f.close()
 
 
print("entering the details of passengers in the pickle file")
write_file()

Now since we have data entered into the file the approach to update data from it is given below along with implementation based on it:

Approach

Program:




import pickle
 
 
def read_file():
   
    f = open("travel.txt", 'rb')
    while True:
        try:
            L = pickle.load(f)
 
            print("Place", L[1], "\t\t Travellers :",
                  L[2], "\t\t Buses :", L[3])
 
        except EOFError:
            print("Completed reading details")
            break
    f.close()
 
 
def update_details():
   
    f1 = open("travel.txt", "rb+")
    travelList = []
    print("For a example i will be updating only Buses details")
    t_code = int(input("Enter the travel code for the updation: "))
     
    while True:
        try:
            L = pickle.load(f1)
            if L[0] == t_code:
                buses = int(input("Enter the number Buses ..."))
                L[3] = buses
            travelList.append(L)
        except EOFError:
            print("Completed Updating details")
            break
             
    f1.seek(0)
    f1.truncate()
     
    for i in range(len(travelList)):
        pickle.dump(travelList[i], f1)
    else:
        f1.close()
 
 
print("update the file")
update_details()
read_file()

Output:


Article Tags :