If I have a fairly large data structure, like a list or a dictionary, and I load it from a pickle file into Python and then only modify one or two records, can I update only those records in the file or do I have to write the entire data structure back to the file? The idea is to avoid excessive and unnecessary hard drive activity, especially writing.
If I can't do that, I guess I need to upgrade to a database?
UPDATE:
I tried @Pynchia's recommendation to use the shelve
module, and it does the job of storing and modifying the data. I only need to confirm that when I modify a single phone number field, that only that one field, or at the most that one record, is written to disk, and not the whole dataset. Is it so or not? That is the question.
import shelve
s = shelve.open('test.dat')
for i in range(3):
record = {'name': 'ABC'+str(i), 'phone': ((str(i)*3)+'-'+(str(i)*4)),
'addr': (str(i)*3)+' Main St'}
s[str(i)] = record
s.close
s = shelve.open('test.dat')
for i in range(3):
print(s[str(i)])
s.close
s = shelve.open('test.dat')
temp = s['1']
temp['phone']='1-800-GET-PYTHON'
s['1']=temp
s.close
print()
s = shelve.open('test.dat')
for i in range(3):
print(s[str(i)])
s.close
Output:
{'name': 'ABC0', 'addr': '000 Main St', 'phone': '000-0000'}
{'name': 'ABC1', 'addr': '111 Main St', 'phone': '111-1111'}
{'name': 'ABC2', 'addr': '222 Main St', 'phone': '222-2222'}
{'name': 'ABC0', 'addr': '000 Main St', 'phone': '000-0000'}
{'phone': '1-800-GET-PYTHON', 'addr': '111 Main St', 'name': 'ABC1'}
{'name': 'ABC2', 'addr': '222 Main St', 'phone': '222-2222'}