I want to deal with the write / read to the file. There is a code:

import pickle result = {'vova':'8', 'stepa': '6', 'primer':'9', 'vovas': '12'} dee = open('dadt.dat','ab') pickle.dump(result,dee) dee.close() dee = open('dadt.dat','rb') der = pickle.load(dee) for i in der: print(i, der[i]) 

What I expect from it is to output what is in the file, if I change the result list — append new values ​​(checking for duplicates beyond the scope of the task).

What I get - the output is correctly made once, but when you change the dictionary and re-write - displays the same thing as the first time.

Let's say change result to

 result = {'vova':'8', 'stepa': '6', 'primer':'9', 'vovas': '12', 'novoe':'12'} 

And I get the same conclusion as in the first case.

Tell me, what am I doing wrong?

    1 answer 1

    Your problem is that you only read the value from the file once. pickle does not allow file synchronization with a variable, so you need to do it yourself every time

    Also, if you open a file for adding (the 'a' key), then the contents of the variable will be written to the end of the file (that is, the second call will contain two variables in the file, the third - three, and so on). The pickle.load function reads only one object from a file in one call, so you have to call it several times to get to the last saved variable.

    If I correctly understood your task, you do not need to store different states of your variable, but only the last but updated one is enough. To do this, open the file for reading (the 'w' key), which will overwrite the file each time you save updates to your variable.

    After that, just save the variable when you need to take into account its updates and load them from the dump file if you need to synchronize with the state written to the file.

     import pickle result = {'vova':'8', 'stepa': '6', 'primer':'9', 'vovas': '12'} # сохраняем словарь в файл with open('dump.dat', 'wb') as dump_out: pickle.dump(result, dump_out) # загружаем словарь из файла with open('dump.dat', 'rb') as dump_in: der = pickle.load(dump_in) for key, value in der.items(): print(key, value) # обновляем словарь result = {'vova':'8', 'stepa': '6', 'primer':'9', 'vovas': '12', 'novoe':'12'} # снова сохраняем словарь в файл with open('dump.dat', 'wb') as dump_out: pickle.dump(result, dump_out) # снова загружаем словарь из файла with open('dump.dat', 'rb') as dump_in: der = pickle.load(dump_in) for key, value in der.items(): print(key, value) 

    Also pay attention to the with construction for working with files and the .items() method of the dictionary, which returns the generator of all the key-value pairs of this dictionary.