سؤال

My (python) application loads a file into memory and lets the user do incremental edits/saves on the data. The data is mostly key/value pairs, so I was thinking of using JSON to represent the information. The application will be a user's only means to access the data, so the exact format of the stored data is driven solely by the application design. The file size will never grow too large, so running out of memory is not a constraint. Every time a user decides to "save", is there a better way of persisting the information to disk than completely wiping the old file and writing the new data?

هل كانت مفيدة؟

المحلول

The object will have to be converted to JSON and written to disk each time you want to save. You might want to investigate whether shelve can meet your needs. You can persist a dictionary to disk using strings as keys and update specific keys as needed...

import shelve
db = shelve.open('data.db')
print db['keyname']
db['keyname'] = 'some new user data'
db.sync()
db.close()

The main advantage of shelve is ease of use. Disadvantages include slow access with big files, lack of cross-system compatibility, and inability to trust files from third-party sources. So if users are expected to email files to each other or otherwise share content over a network, shelve would not be a secure choice.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top