Can You Permanently Change Python Code By Input?
Solution 1:
There are planty of methods how you can make your data persistent. It depends on the task, on the environment etc. Just a couple examples:
- Files (JSON, DBM, Pickle)
- NoSQL Databases (Redis, MongoDB, etc.)
- SQL Databases (both serverless and client server: sqlite, MySQL, PostgreSQL etc.)
The most simple/basic approach is to use files. There are even modules that allow to do it transparently. You just work with your data as always.
See shelve
for example.
From the documentation:
A “shelf” is a persistent, dictionary-like object. The difference with “dbm” databases is that the values (not the keys!) in a shelf can be essentially arbitrary Python objects — anything that the pickle module can handle. This includes most class instances, recursive data types, and objects containing lots of shared sub-objects. The keys are ordinary strings.
Example of usage:
importshelves= shelve.open('test_shelf.db')
try:
s['key1'] = { 'int': 10, 'float':9.5, 'string':'Sample data' }
finally:
s.close()
You work with s
just normally, as it were just a normal dictionary.
And it is automatically saved on disk (in file test_shelf.db
in this case).
In this case your dictionary is persistent and will not lose its values after the program restart.
More on it:
Another option is to use pickle, which gives you persistence also, but not magically: you will need read and write data on your own.
Comparison between shelve
and pickle
:
Post a Comment for "Can You Permanently Change Python Code By Input?"