I'm trying to make an address book on the book Byte of Python.

Trying to delete a contact from a file:

def delete_person(self): f = open('mybook.txt', 'ab+') allcontacts = pickle.load(f) deluser = input('Введите имя того, кого хотите удалить?') del allcontacts[deluser] f = allcontacts pickle.dump(PhoneBook.mybook, f) f.close() 

What could be the problem? I tried to insert different modes of reading and writing to the file.

Gives an error message:

 Traceback (most recent call last): File "C:/PythonWork/Kate/phonebookclassi.py", line 81, in <module> phonebook.delete_person() File "C:/PythonWork/Kate/phonebookclassi.py", line 36, in delete_person allcontacts = pickle.load(f) EOFError: Ran out of input 
  • Try opening the file in read mode 'rb' . - mkkik
  • So I need to read and then write down (that is, fill the dictionary with the deleted item) - kelevra
  • Open the file, read the dictionary, close the file, delete the dictionary item, open the file (in write mode), write the dictionary, close the file. Pickle , it seems, does not support anything except wb / rb . - mkkik

1 answer 1

You can only read or write. Not at the same time. If you populate a few pickle objects into a file, then you need to read them from there sequentially, until the end of the file is reached. Something like this:

 import pickle obj1 = {"foo": "bar"} obj2 = {"eggs": "spam"} obj3 = {"blah": "blah"} with open("dump.pkl", "a+b") as f: pickle.dump(obj1, f) pickle.dump(obj2, f) pickle.dump(obj3, f) with open("dump.pkl", "rb") as file: objects = [] while True: try: objects.append(pickle.load(file)) except EOFError: break print(objects) >>> [{'foo': 'bar'}, {'eggs': 'spam'}, {'blah': 'blah'}] 

And Ran out of input occurs when the file is empty or damaged.