Having problems pickling and loading for class - python

So the prompt is:
Phase 1: Employee Class
Write a class named Employee that holds the following data about an employee in attributes: name, ID Number, department, and job title.
Once you have written the class, write a program that creates three Employees objects to hold the following data:
Name, ID Number, Department, Job Title
Susan Meyers 47899 Accounting Vice President
Mark Jones 39119 IT Programmer
Joy Rodgers 81774 Manufacturing Engineer
The program should store this data in the three objects, then display the data for each employee on the screen.
Phase 2: Employee Management System
This exercise assumes you have created the Employee class for Phase 1. Create a program that stores Employee objects in a dictionary. Use the employee ID number as the key. The program should present a menu that lets the user perform the following actions:
Look up an employee in the dictionary
Add a new employee to the dictionary
Change an existing employee's name, department, and job title in the dictionary
Delete an employee from the dictionary
Quit the program
When the program ends, it should pickle the dictionary and save it to the file. Each time the program starts, it should try to load the pickled dictionary from the file. If the file does not exist, the program should start with an empty dictionary.
SO for the most part I was able to create the class, and I was able to create the menu, I'm having problems with putting the employees in the file and loading so that I can use the menu. Here's my code:
import EmployeeClass
import pickle
def lookup(dictionary):
id_num = input("What is the employee's ID number")
if id_num in dictionary.keys():
print(id_num, ":", dictionary[id_num].str())
else:
print("I'm sorry we don't have that number in our registry. Try again")
lookup(dictionary)
def add(dictionary):
name = input("What is their name?")
id_num = input("What is their ID number?")
department = input("What department do they work in?")
title = input("What position do they hold?")
entry = EmployeeClass.Employee(name, id_num, department, title)
dictionary[id_num] = entry
return dictionary
def change(dictionary):
id_num = input("Enter the ID Number off the employee you would like to change:")
if id_num in dictionary.keys():
tempID = id_num
newName = input("What would you like to change the name to?")
newID = input("What would you like to change their ID Number to?")
newDepartment = input("What department does this person work in?")
newTitle = input("What title does this person hold?")
entry = EmployeeClass.Employee(newName, newID, newDepartment, newTitle)
dictionary[newID] = entry
del dictionary[tempID]
print("Employee changed successfully")
else:
print("Employee not found. Try again")
def delete(dictionary):
id_num = input("Enter the ID Number of the employee that would like to delete")
if id_num in dictionary.keys():
del dictionary[id_num]
else:
print("That employee was not found")
def save_close(dictionary):
output_file = open('employee.dat', 'wb')
pickle.dump(dictionary, output_file)
output_file.close()
def main():
employee_data = open("employee.dat", 'wb')
emp1 = EmployeeClass.Employee("Susan Myers", 47899, "Accounting", "Vice President")
emp2 = EmployeeClass.Employee("Mark Jones", 39119, "IT", "Programmer")
emp3 = EmployeeClass.Employee("Joy Rodgers", 81774, "Manufacturing", "Engineer")
pickle.dump(emp1, employee_data)
pickle.dump(emp2, employee_data)
pickle.dump(emp3, employee_data)
employee_data.close()
input_file = open('employee.dat', 'rb')
pickle.load(input_file)
input_file.close()
employee_dictionary = {}
next = True
while next:
print("Welcome to the the Employee Management System. Would you like to:\n")
print("Lookup an employee? Press 1 \n")
print("Add a new employee? Press 2 \n")
print("Alter an existing employee? Press 3 \n")
print("Delete an existing employee's information? Press 4 \n")
print("Save and Close? Press 5 \n")
user_choice = input(int())
menu = {"1": lookup, "2": add, "3": change, "4": delete, "5": save_close}
x = menu[user_choice](employee_dictionary)
if user_choice == 2:
employee_dictionary.update(x)
if user_choice ==3:
employee_dictionary.update(x)
if user_choice ==4:
employee_dictionary.update(x)
main()
So luckily I was able to figure out the pickling problem thanks to someone who answered, but after that when loading the menu it says that my Employee object has not attribute keys. Thank you for your responses!

What you're doing wrong is you're not assigning the depickled file to any variable.
You need to change this block of code
input_file = open('employee.dat', 'rb')
pickle.load(input_file)
input_file.close()
employee_dictionary = {}
to
input_file = open('employee.dat', 'rb')
employee_dictionary=pickle.load(input_file)
input_file.close()
Only then would you be able to access the pickled dictionary.

Related

Saving an Object and being able to update its attributes

I am creating a POS system in Python, which is almost complete. (GUI not included). However, I want to be able to store the items that a user registers.
I tried saving the object to a file, but that did not help:
with open('myObject.pkl', 'wb') as outp:
itemObject = Item("", 0, 0)
pickle.dump(itemObject, outp, pickle.HIGHEST_PROTOCOL)
Even after I input the item's details ("name",price,stock) an exit the program, when I started it again I had to register the item all over again.
I also searched online on the matter, but all the results I got did not support updating the attributes of the object in the file.
I've also checked more examples on the forum, but none of them suit my needs well, like this one: Saving an Object (Data persistence), Python- Saving list of objects and its attributes
If it helps, here is where I defined the class and object:
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
itemObject = Item("", 0, 0)
Here is the function that updates the class attributes based on user input:
def regItem():
name = input("What is your item called? ")
name.lower()
if name == 'exit':
exit()
try:
price = int(input("How much does it cost? "))
name.lower()
if name == 'exit':
exit()
if (isinstance(price, int)):
stock = input("How much stock is available for this item? ")
name.lower()
if name == 'exit':
exit()
itemObject.name = name
itemObject.price = price
itemObject.stock = stock
int(itemObject.price)
int(itemObject.stock)
print("Item",itemObject.name,"priced at",itemObject.price,"with available stock of",itemObject.stock,"has been registered")
start()
except ValueError:
print("Must be a number")
regItem()
I'm learning Python as my first language, and I'm also new to stack overflow. Any help would be appreciated. Thanks in advance.
You need to conditionally load the object you are trying to persist.
import os
import pickle
class Item:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def __str__(self):
return f"Item {self.name} priced at {self.price} with available stock of {self.stock}"
def regItem():
name = input("What is your item called? ")
name.lower()
if name == 'exit':
exit()
try:
price = int(input("How much does it cost? "))
name.lower()
if name == 'exit':
exit()
if (isinstance(price, int)):
stock = input("How much stock is available for this item? ")
name.lower()
if name == 'exit':
exit()
itemObject = Item(name, price, stock)
print(f"{itemObject} has been registered")
return itemObject
except ValueError:
print("Must be a number")
return regItem()
def start(obj):
print("Starting {}".format(obj))
def main():
filename = 'myObject.pkl'
if os.path.exists(filename):
with open(filename, 'rb') as inp:
itemObject = pickle.load(inp)
else:
itemObject = regItem()
with open('myObject.pkl', 'wb') as outp:
pickle.dump(itemObject, outp, pickle.HIGHEST_PROTOCOL)
start(itemObject)
main()
Run this once to enter in the data. Run it again and it will start with the same object you started with.

How can I create an input that will loop and create a new list each time?

in case it isn't already obvious im new to python so if the answers could explain like im 5 years old that would be hugely appreirecated.
I'm basically trying to prove to myself that I can apply some of the basic that I have learnt into making a mini-contact book app. I don't want the data to save after the application has closed or anything like that. Just input your name, phone number and the city you live in. Once multiple names are inputted you can input a specific name to have their information printed back to you.
This is what I have so far:
Name = input("enter name here: ")
Number = input("enter phone number here: ")
City = input("enter city here: ")
User = list((Name, Number, City))
This, worked fine for the job of giving python the data. I made another input that made python print the information back to me just to make sure python was doing what I wanted it to:
print("Thank you! \nWould you like me to read your details back to you?")
bck = input("Y / N")
if bck == "Y":
print(User)
print("Thank you! Goodbye")
else:
print("Goodbye!")
The output of this, is the list that the user creates through the three inputs. Which is great! I'm happy that I have managed to make it function so far;
But I want the 'Name' input to be what names the 'User' list. This way, if I ask the user to input a name, that name will be used to find the list and print it.
How do I assign the input from Name to ALSO be what the currently named "User" list
You will need to create a variable which can store multiple contacts inside of it. Each contact will be a list (or a tuple. Here I have used a tuple, but it doesn't matter much either way).
For this you could use a list of lists, but a dictionary will be more suitable in this case.
What is a dictionary?
A dictionary is just like a list, except that you can give each of the elements a name. This name is called a "key", and it will most commonly be a string. This is perfect for this use case, as we want to be able to store the name of each contact.
Each value within the dictionary can be whatever you want - in this case, it will be storing a list/tuple containing information about a user.
To create a dictionary, you use curly brackets:
empty_dictionary = {}
dictionary_with_stuff_in_it = {
"key1": "value1",
"key2": "value2"
}
To get an item from a dictionary, you index it with square brackets, putting a key inside the square brackets:
print(dictionary_with_stuff_in_it["key1"]) # Prints "value1"
You can also set an item / add a new item to a dictionary like so:
empty_dictionary["a"] = 1
print(empty_dictionary["a"]) # Prints 1
How to use a dictionary here
At the start of the code, you should create an empty dictionary, then as input is received, you should add to the dictionary.
Here is the code I made, in which I have used a while loop to continue receiving input until the user wants to exit:
contacts = {}
msg = "Would you like to: \n - n: Enter a new contact \n - g: Get details for an existing contact \n - e: Exit \nPlease type n, g, or e: \n"
action = input(msg)
while action != "e":
if action == "n": # Enter a new contact
name = input("Enter name here: ")
number = input("Enter phone number here: ")
city = input("Enter city here: ")
contacts[name] = (number, city)
print("Contact saved! \n")
action = input(msg)
elif action == "g": # Get details for an existing contact
name = input("Enter name here: ")
try:
number, city = contacts[name] # Get that contact's information from the dictionary, and store it into the number and city variables
print("Number:", number)
print("City:", city)
print()
except KeyError: # If the contact does not exist, a KeyError will be raised
print("Could not find a contact with that name. \n")
action = input(msg)
else:
action = input("Oops, you did not enter a valid action. Please type n, g, or e: ")
#can be easier to use with a dictionary
#but its just basic
#main list storing all the contacts
Contact=[]
#takes length of contact list,'int' just change input from string to integer
contact_lenght=int(input('enter lenght for contact'))
print("enter contacts:-")
#using for loop to add contacts
for i in range(0,len(contact_lenght)):
#contact no.
print("contact",i+1)
Name=input('enter name:')
Number=input('enter number:')
City=input("enter city:")
#adding contact to contact list using .append(obj)
Contact.append((Name,Number,City))
#we can directly take input from user using input()
bck=input("Thank you! \nWould you like me to read your details back to you?[y/n]:")
#checking if user wants to read back
if bck=='y':
u=input("enter your name:")
#using for loop to read contacts
for i in range(0,len(Contact)):
#if user name is same as contact name then print contact details
if u==Contact[i][0]:
print("your number is",Contact[i][1])
print("your city is",Contact[i][2])
else:
#if user doesnt want to read back then print thank you
print("Good bye")
For this purpose you should use a dictionary.
The key of every entry should be the string 'User[0]' that corresponds to the person's name.
The contents of every entry should be the list with the information of that user.
I'll give you an example:
# first we need to create an empty dictionary
data = {}
# in your code when you want to store information into
# the dictionary you should do like this
user_name = User[0] # this is a string
data[user_name] = User # the list with the information
If you want to access the information of one person you should do like this:
# user_you_want string with user name you want the information
data[user_you_want]
Also you can remove information with this command:
del data[user_you_want_to_delete]
You can get more information on dictionaries here: https://docs.python.org/3/tutorial/datastructures.html#dictionaries
You should start by defining a class to support name, phone and city. Once you've done that, everything else is easy.
class Data:
def __init__(self, name, city, phone):
self.name = name
self.city = city
self.phone = phone
def __eq__(self, other):
if isinstance(other, str):
return self.name == other
if isinstance(name, type(self)):
return self.name == other.name and self.city == other.city and self.phone == other.phone
return False
def __str__(self):
return f'Name={self.name}, City={self.city}, Phone={self.phone}'
DataList = []
while (name := input('Name (return to finish): ')):
city = input('City: ')
phone = input('Phone: ')
DataList.append(Data(name, city, phone))
while (name := input('Enter name to search (return to finish): ')):
try:
print(DataList[DataList.index(name)])
except ValueError:
print('Not found')

how do we grab a specific information like the name from this?

I'm looking at this example and I want to figure out how can I search up a name instead of the ID, then display all the information for the name? For example if it has the ID of 1, name: Bob, department: sales, and job title: manager. If we search up "Bob", everything will display. Sorry this is long.
class Employee:
def __init__(self, name, ID, department, job_title):
self.__name = name
self.__ID = ID
self.__dept = department
self.__job = job_title
def set_name(self, name):
self.__name = name
def set_department(self, department):
self.__dept = department
def set_job_title(self, job_title):
self.__job = job_title
def get_name(self):
return self.__name
def get_ID_number(self):
return self.__ID
def get_department(self):
return self.__dept
def get_job_title(self):
return self.__job
def __str__(self):
return 'Name: ' + self.__name + '\n' + \
'ID Number: ' + str(self.__ID) + '\n' + \
'Department: ' + self.__dept + '\n' + \
'Job Title: ' + self.__job
import pickle
def pickle_it(employees):
# Open file in binary write mode
output_file = open('employees.dat', 'wb')
# Write the data to the file
pickle.dump(employees, output_file)
# Close the file
output_file.close()
def unpickle_it():
try:
# Attempt to open file in binary read mode
input_file = open('employees.dat', 'rb')
except IOError:
# If the file doesn't exist, then create it by opening using write
# mode. Then just close and reopen in binary read mode.
file = open('employees.dat', 'wb')
file.close()
input_file = open('employees.dat', 'rb')
# Load the employees dictionary or create an empty dictionary if file is
# empty
try:
employees = pickle.load(input_file)
except:
employees = {}
# Close the file
input_file.close()
# Return the employees dictionary
return employees
import menu_choices
import save_load_dict
# Global constants for menu choices
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def main():
employees = save_load_dict.unpickle_it()
choice = menu_choices.get_menu_choice()
while choice != QUIT:
if choice == LOOK_UP:
menu_choices.look_up(employees)
elif choice == ADD:
menu_choices.add(employees)
elif choice == CHANGE:
menu_choices.change(employees)
elif choice == DELETE:
menu_choices.delete(employees)
choice = menu_choices.get_menu_choice()
save_load_dict.pickle_it(employees)
main()
import employee_class
# Global constants for menu choices
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5
def get_menu_choice():
print('\n\033[4m' + 'Employee Directory' + '\033[0m')
print('1. Look up an employee')
print('2. Add a new employee')
print('3. Edit an employee\'s information')
print('4. Delete an employee')
print('5. Quit\n')
# Get the user's choice.
choice = int(input('Enter your choice: '))
# Validate the choice.
while choice < LOOK_UP or choice > QUIT:
choice = int(input('Enter a valid choice: '))
# return the user's choice.
return choice
# The look_up function looks up an employee and displays their information.
def look_up(employees):
# Get a name to look up.
ID = input('Enter an employee ID number: ')
# Look it up in the dictionary.
if ID in employees:
print(employees[ID])
else:
print('That ID number is not found.')
# The add function adds a new entry into the dictionary.
def add(employees):
# Get employee information.
name = input('Enter the employee\'s name: ')
ID = input('Enter the employee\'s ID number: ')
department = input('Enter the employee\'s department: ')
job_title = input('Enter the employee\'s job title: ')
# If the name does not exist, add it.
if ID not in employees:
employees[ID] = employee_class.Employee(name, ID, department, \
job_title)
else:
print('An entry with that ID number already exists.')
Your question heading asks for how to search using email while the class Employee has no email attribute.
To search using other attribute like Name:
Though the code snippets you pasted doesn't define what employees object is, it's a dict mapping between id and corresponding Employee object.
If you only need to search by name, you can make the employees dictionary as a mapping between Name and Employee objects (list, as multiple employee can have same name).
If you need a more dynamic solution that lets you search by just about anything, then you need to match with all attributes of each Employee object. And also will need to take care of case insensitivity in search.
def look_up(employees):
# Get any searchtext to lookup
searchtext = input('Enter search query to lookup')
matches = [emp for emp in employees.values()
if searchtext.lower() in [
emp.get_name().lower(),
emp.get_ID_number(), # Add .lower() if needed
emp.get_department().lower(), #.lower() for case insensitive match
emp.get_job_title().lower()
]
]
if not matches:
print(f'No employee matches any attribute for searchtext {searchtext}')
return None
# If there are valid matches
print(matches)
Eliminate any of the above fields if not needed.
You can go more crazier in terms of matching the string with partial matches like doing searchtext in candidate for candidate in [emp.<some_attributes>,..] or use levenshtein distance.
You'll need to take into account that two employees could have the same name. The following code (adapted from your existing look_up function) will return all the employees with the name specified, or a message that there are no employees with that name :
# The look_up function looks up an employee by name and displays their information.
def look_up_by_name(employees):
# Get a name to look up.
name = input('Enter an employee Name: ')
matches = [emp for emp in employees if emp['name'] == name]
if len(matches) == 0:
print('No employees with name "{}" found'.format(name))
else:
for m in matches:
print(m)

User input not saving into inventory list

Basically I am making an app to better assist me at managing my ebay store. I am still very new to programming and OOP. After watching some tutorials I pieced together the following code. Everything so far works pretty well. What I am currently stuck on is when the user inputs an item for inventory, it is not saving it. And, when the user wants to view the inventory the item they added wont populate. Any input or suggestions would be much apprenticed.
def Inventory():
All_Inventory = {}
class Ebay_Inventory:
def __init__(self, manufacturer, object_type, price):
self.manufacturer = manufacturer
self.object_type = object_type
self.price = price
def add_item(self):
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item_info = Ebay_Inventory(manufacturer, object_type, price)
All_Inventory = item_info
print("Item added successfully")
def delete_item(self):
delete = input("What is the item you want to delete?: ")
if delete in All_Inventory.keys():
del[delete]
print("The item entered has been deleted.")
else:
print("Item not found")
def sale_status(self):
update = input("What is the item you want to update?:")
if update in All_Inventory.keys():
pass
else:
print("Item not found")
user=True
while user:
print("\n1. Add to item inventory")
print("2. Remove item from inventory")
print("3. Update sale status")
print("4. View inventory")
print("5. Exit program")
user_wants=input("What would you like to do today?")
if user_wants=="1":
Ebay_Inventory.add_item(input)
elif user_wants=="2":
Ebay_Inventory.delete_item(input)
elif user_wants=="3":
Ebay_Inventory.sale_status(input)
elif user_wants=="4":
print(All_Inventory)
elif user_wants=="5":
print("\n Thank you for using item inventory.")
break
elif user_wants!="":
print("\n Input not understood. Please try again.")
You need to read about Scope, OOP and dicts:
You are not adding to your Inventory.All_Inventory - you create a new local with All_Inventory = item_info
https://docs.python.org/3/tutorial/classes.html#python-scopes-and-namespaces
Short description of the scoping rules?
You mix up static class attributes and instance attributes, read:
https://docs.python.org/3/tutorial/classes.html#class-objects.
What is the difference between #staticmethod and #classmethod?
You are deleting / accessing your dictionary wrongly - see :
https://docs.python.org/3/tutorial/datastructures.html#dictionaries
Delete an element from a dictionary
Fixed:
class Ebay_Inventory:
Inventory = {} # class property
#staticmethod
def print_inventory():
for k in Ebay_Inventory.Inventory:
for i in Ebay_Inventory.Inventory[k]:
print(k,i)
class Ebay_Item:
def __init__(self, key, manufacturer, object_type, price):
self.manufacturer = manufacturer
self.object_type = object_type
self.price = price
self.key = key
def __str__(self):
return f"{self.manufacturer} {self.object_type} {self.price}"
def __repr__(self):
return str(self)
#staticmethod
def add_item(key=None, man=None, obj=None, pri=None):
# use values if given, else ask - this is for demo purposes only
key = key or input("Enter key: ")
manufacturer = man or input("Enter Manufacturer: ")
object_type = obj or input("Enter what the item is: ")
price = pri or input("Enter price: ")
# create new item
item_info = Ebay_Inventory.Ebay_Item(key, manufacturer, object_type, price)
# add to class member, create key if need be
Ebay_Inventory.Inventory.setdefault(item_info.key,[]).append(item_info)
def delete_item(key=None):
delete = key or input("What is the item you want to delete?: ")
if delete in Ebay_Inventory.Inventory:
del Ebay_Inventory.Inventory[delete]
print("The item entered has been deleted.")
else:
print("Item not found")
def __str__(self):
return Ebay_Inventory.print_inventory()
# add 2 items and print
Ebay_Inventory.add_item(1,"Me","Me",1000)
Ebay_Inventory.add_item(2,"You","You",1000)
Ebay_Inventory.print_inventory()
# remove non existent and existent item and print
Ebay_Inventory.delete_item(3)
Ebay_Inventory.delete_item(2)
Ebay_Inventory.print_inventory()
Output:
1 Me Me 1000
2 You You 1000
Item not found
The item entered has been deleted.
1 Me Me 1000
Sorry to rework your code pretty extensively, but I think this is more like what you are going for:
class EbayInventory:
def __init__(self):
self.all_inventory = []
def print_items(self):
print('Current item list by index:')
for i in range(0, len(self.all_inventory)):
print("{} -> {}".format(i+1, self.all_inventory[i]))
def add_item(self):
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item = {'manufacturer': manufacturer, 'type': object_type, 'price': price}
self.all_inventory.append(item)
print("Item added successfully")
def delete_item(self):
self.print_items()
delete = int(input("Item id you want to delete: "))
try:
del self.all_inventory[delete - 1]
print("The item entered has been deleted.")
except Exception as e:
print("An error occurred deleting that item, details below")
print(e)
def sale_status(self):
self.print_items()
update_index = int(input("Item id you want to update: "))
if update_index > len(self.all_inventory) or update_index <= 0:
print("You're trying to change an item that doesn't exist!!")
return
print("OK. Let's get that item up to date!")
manufacturer = input("Enter Manufacturer: ")
object_type = input("Enter what the item is: ")
price = input("Enter price: ")
item = {'manufacturer': manufacturer, 'type': object_type, 'price': price}
self.all_inventory[update_index - 1] = item
print("OK. We got that update taken care of")
if __name__ == "__main__":
my_app = EbayInventory()
while True:
print("\n1. Add to item inventory")
print("2. Remove item from inventory")
print("3. Update sale status")
print("4. View inventory")
print("5. Exit program")
user_wants = input("Please enter the number corresponding to how you would like help: ")
if user_wants == "1":
my_app.add_item()
elif user_wants == "2":
my_app.delete_item()
elif user_wants == "3":
my_app.sale_status()
elif user_wants == "4":
my_app.print_items()
elif user_wants == "5":
print("Thank you for using item inventory.")
break
else:
print("Input not understood. Please try again.")
You had a variable user that did nothing. You can simply enter an infinite loop with while True:. If you wanted to loop the way you did, then instead of a break you could have put a user = False to break out of the loop. This is sometimes a nifty trick, but doesn't make sense here I think. It seemed to me the inventory was really the only thing that would benefit by being stored in your class, and the methods could then access it to adjust it via a self.all_inventory. I moved your code to ask for item inputs to the add_item() and sale_status() methods, so now the main block of code looks a lot cleaner. I also wrapped it in if __name__ == "__main__": so that you can import this class to another project without running the entire program! I threw in some basic error checking with try: and except: clauses also. I think you were misunderstanding the difference between a Class and an Instance. So in my code the Class is EbayInventory, but the Instance is my_app. You create instances of your class just like I did with my_app = EbayInventory() and then the self now refers to my_app. In this manner I can call my_app.add_item(). You can have several instances of objects though, and they each have their own space in your computers memory. So you could have said:
app1 = EbayInventory()
app2 = EbayInventory()
app1.add_item()
And only the app1 will have any items, whereas app2 is still an empty list, but still has the methods to build an inventory via app2.add_item(). To answer your main question though, you never call your function Inventory() and therefore it doesn't exist to hold your information. When you call item_info = Ebay_Inventory(manufacturer, object_type, price) in fact you are making an Instance of a class, which is really nonsensical to do here because that means on the next line you could say item_info.add_item() and this would make another instance, yet you are not saving this information anywhere so you can never retrieve it!

How to delete the pickled object from a file?

I've got a problem while I was doing a program. My program is to create a class student and there are some variables under that and my task is to add the students in a serializable file and delete the students whenever user wants to. I have written the code for adding the students but I am stuck while delete the object. I am very thankful if anyone could help me how to delete a pickled object from a file?
my code is:
import pickle
n = int(input("Enter number of students you want to enter:"))
for i in range(0,n):
name = input("Enter student name: ")
roll = input("Enter roll number: ")
sex = input("Enter sex: ")
sub = input("Enter subject: ")
tot = input("Enter total: ")
s = Student(name,roll,sex,sub,tot)
infile = open("pb.txt","ab")
pickle.dump(s,infile)
infile.close()
and my student class is:
class Student:
def __init__(self,name,roll,sex,sub,tot):
self.name = name
self.roll = roll
self.sex = sex
self.sub = sub
self.tot = tot
One way could be to pickle a list of students. Then when you want to delete, you can read from file, delete as normal e.g. students.remove(), and then pickle again.
Pickle files aren't editable, and they were never meant to be. If you need to track individual pickled items, look at the shelve module - this lets you treat an external collection of (pickled) objects like a dictionary with string keys.

Categories