Apr-02-2020, 03:05 PM
Hi,
The code below runs as designed when executed the first time. It creates a file with binary data. Because on the first run the file doesn't exist, a warning is printed. However, the same warning is printed when the code is executed a second time. I don't understand why the warning it shoed the second time when the file does have data.
Any help is appreciated.
TIA
The code below runs as designed when executed the first time. It creates a file with binary data. Because on the first run the file doesn't exist, a warning is printed. However, the same warning is printed when the code is executed a second time. I don't understand why the warning it shoed the second time when the file does have data.
Any help is appreciated.
TIA
import pickle class People: def __init__(self, name, gender, age): self.name=name self.gender=gender self.age=age print("A new person has been added with the name of: ", self.name) def __str__(self): return "{} {} {}".format(self.name, self.gender, self.age) class PeopleList: people=[] def __init__(self): listOfPeople=open("externalFile", "ab+") #reset cursor position listOfPeople.seek(0) #just in case on the first run the file is empty try: self.people(pickle.load(listOfPeople)) print("{} people have been loaded".format(len(self.people))) except: print("The file is empty") finally: listOfPeople.close() #del(listOfPeople) def addPeople(self, p): self.people.append(p) self.savePeopleToFile() def showPeople(self): for p in self.people: print(p) def savePeopleToFile(self): listOfPeople=open("externalFile", "wb") pickle.dump(self.people, listOfPeople) listOfPeople.close() del(listOfPeople) def showExternalFileInfo(self): print("File info:") for p in self.people: print(p) myList=PeopleList() p=People("Roman", "male", 59) myList.addPeople(p) #p=People("Mike", "male", 29) #myList.addPeople(p) #p=People("Rosa", "female", 48) #myList.addPeople(p) #p=People("Maria", "female", 28) #myList.addPeople(p) myList.showExternalFileInfo()