Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to delete data from file in Python
Next article icon

How to delete from a pickle file in Python?

Last Updated : 29 Sep, 2021
Comments
Improve
Suggest changes
Like Article
Like
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:


Next Article
How to delete data from file in Python
author
rohit2sahu
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Technical Scripter 2020
  • python-utility
Practice Tags :
  • python

Similar Reads

  • How to delete data from file in Python
    When data is no longer needed, it’s important to free up space for more relevant information. Python's file handling capabilities allow us to manage files easily, whether it's deleting entire files, clearing contents or removing specific data. For more on file handling, check out: File Handling in P
    3 min read
  • How to delete a CSV file in Python?
    In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Ap
    2 min read
  • Delete pages from a PDF file in Python
    In this article, We are going to learn how to delete pages from a pdf file in Python programming language. Introduction Modifying documents is a common task performed by many users. We can perform this task easily with Python libraries/modules that allow the language to process almost any file, the
    4 min read
  • How to search a pickle file in Python?
    Prerequisites: pickle file  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 conver
    3 min read
  • 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, d
    3 min read
  • How to Read from a File in Python
    Reading from a file in Python means accessing and retrieving the contents of a file, whether it be text, binary data or a specific data format like CSV or JSON. Python provides built-in functions and methods for reading a file in python efficiently. Example File: geeks.txt Hello World Hello Geeksfor
    5 min read
  • How to open and close a file in Python
    There might arise a situation where one needs to interact with external files with Python. Python provides inbuilt functions for creating, writing, and reading files. In this article, we will be discussing how to open an external file and close the same using Python. Opening a file in Python There a
    4 min read
  • How to Unpack a PKL File in Python
    Unpacking a PKL file in Python is a straightforward process using the pickle module. It allows you to easily save and load complex Python objects, making it a useful tool for many applications, especially in data science and machine learning. However, always be cautious about the security implicatio
    3 min read
  • How to remove blank lines from a .txt file in Python
    Many times we face the problem where we need to remove blank lines or empty spaces in lines between our text to make it look more structured, concise, and organized. This article is going to cover two different methods to remove those blank lines from a .txt file using Python code. This is going to
    3 min read
  • How to Delete Only Empty Folders in Python
    In this article, we are going to see how to delete only empty folders in Python. Before deleting the folder, here is an image showing the files inside the main directory. As the above image is showing that the folder has 2 empty sub-folders and 1 non-empty folder. So, after running the code these 2
    1 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences