Trying To Implement A Cache On Load Of This File
Solution 1:
You can actually maintain order with a single file, using a combination of json
and collections.OrderedDict
.
Your initial setup is like so:
from collections importOrderedDictphone_book= OrderedDict({})
When creating, add elements into an ordered dict and then dump it as JSON. The order of keys is preserved. After you declared phone_book
like above, the rest of the code for create
remains the same. Note that when you write to the file, you don't close it, so you can't read the contents later. This should be replaced with something like:
import os
if os.path.exists("qwerty.json")
phone_book = json.load(open("qwerty.json", "r"), object_pairs_hook=OrderedDict)
else:
phone_book = OrderedDict({})
command = ""whilecommand != 'exit':
command = input('Enter a command(options: create,read,save): ')
ifcommand == "create":
...
elifcommand == 'read':
...
elifcommand == 'save':
json.dump(phone_book, open('qwerty.json', "w"))
For reading, you'll have to make some changes:
elifcommand == 'read':
z = json.load(open("C:\\Users\\qwerty.txt", "r"), object_pairs_hook=OrderedDict)
...
This loads the dict in the order the keys were stored. You can now call list(z.items())[-20:]
to get only the last 20 items. Also, when reading a particular key, you update its "last-read-time" by deleting and recreating it:
importcopy
key = ...
temp = copy.copy(z[key])
del z[key]
z[key] = temp
This will update the position of key
in the dict. This should be enough for you to implement the rest yourself.
Post a Comment for "Trying To Implement A Cache On Load Of This File"