So, I'm still learning how to use pickle, and have a limited knowledge of it. This may be a beginner question... I created this placeholder class:
class Student:
def __init__(self):
self.__name = ""
self.__regNum = 0
self.__fullTime = True
def getName(self):
return self.__name
def getRegNum(self):
return self.__regNum
def getFullTime(self):
return self.__fullTime
def setName(self,name):
self.__name = name
def setRegNum(self,num):
self.__regNum = num
def setFullTime(self,fullTime):
self.__fullTime = bool(fullTime)
I created two test students:
student1 = Student()
student1.setName("Joe")
student1.setRegNum(2110)
student1.setFullTime(1)
student2 = Student()
student2.setName("Jess")
student2.setRegNum(5124)
student2.setFullTime(0)
dumpFile = open("student.DAT","wb")
pickle.dump(student1,dumpFile)
pickle.dump(student2,dumpFile)
dumpFile.close()
loadFile = open("student.DAT","rb")
- but I don't know how to read both separately after loading the .dat file as separate objects.
I tried to use the with open("student.dat", 'rb') as input: that I've seen on the internet, but I have no clue what it does to understand why it's not working. I tried numpy.fromfile but I don't understand the outcome I get, and I've seen people use pandas but I don't know a thing. I can't really understand what the solutions are when I look it up, what should I do?
I would suggest you to dump a
list of objectsinto your.datfile and retrieve that later while loading.Then you can just iterate through
datato access each object separately.As with the case of using
with open, its easy to understand. In simple words, it ensures that you dont have to close your file after use. For example the same code can be written as: