Open In App

How to delete from a pickle file in Python?

Improve
Improve
Like Article
Like
Save
Share
Report

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 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:

  • dump()– used to write a pickled representation of obj to the open file object file.

Syntax:

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

  • load()– used to read a pickled object representation from the open file object file and return the reconstituted object hierarchy specified.

Syntax:

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

  • seek(0)- Pickle records can be concatenated into a file, so yes, you can just pickle.load(f) multiple times, but the files themselves are not indexed in a way that would let you seek into a given record. What your f.seek(0) is doing is seeking into the third byte in the file, which is in the middle of a pickle record, and thus is unpicklable. If you need random access, you might want to look into the built-in shelve module which builds a dictionary-like interface on top of pickle using a database file module.
  • truncate()- changes the file size

To delete contents from a pickle file we first need to add contents to it, given below is an approach for doing the same along with its implementation:

Approach

  • Import module
  • Open file in write mode
  • Enter data
  • Dump data to the file
  • Continue until the choice is yes
  • Close file

Program:

Python3




import pickle
 
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 delete data from it is given below along with implementation based on it:

Approach

  • Import module
  • Open file
  • Enter some information regarding data to be deleted
  • Delete appropriate data
  • Close file

Program:

Python3




import pickle
 
 
def delete_details():
   
    f1 = open("travel.txt", 'rb+')
    travelList = []
    t_place = input("Enter the place to delete :")
 
    while True:
        try:
            L = pickle.load(f1)
            if(L[1] != t_place):
                travelList.append(L)
        except EOFError:
            print("completed deleting details")
            break
 
    f1.seek(0)
    f1.truncate()
 
    for i in range(len(travelList)):
        pickle.dump(travelList[i], f1)
    else:
        f1.close()
 
# reading content in the file.
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()
 
 
print("deleting the desired column")
delete_details()
 
print("Reading the file")
read_file()


Output:



Last Updated : 29 Sep, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads