Skip to content

Instantly share code, notes, and snippets.

@axju
Last active September 25, 2019 19:59
Show Gist options
  • Save axju/a0ba9acfbb81b868646ea2337c29fcaf to your computer and use it in GitHub Desktop.
Save axju/a0ba9acfbb81b868646ea2337c29fcaf to your computer and use it in GitHub Desktop.
A small example of how you can save and load data.
"""
A small example of how you can save and load data.
If the value does not exist, default values ​​are used. It also allows additional
data. The data is stored in a fixed location. If you want to use this in your
project, you have to customize that.
Author: AxJu
"""
import os
import json
DEFAULTS = {
'name': 'AxJu',
'foo': 'spam',
}
def load():
"""
This function returns the data from your configuration file. If this file
is not available, it use the default values. The default values ​​will also
be loaded if some values ​​are missing.
"""
# Get the home directory and create your config filename.
# You should customize the filename for your project.
home = os.path.expanduser('~')
filename = os.path.join(home, 'yoursettings.json')
# Load all default values.
result = dict(DEFAULTS)
# If the file exists, load the data with json.
if os.path.exists(filename):
with open(filename) as file:
data = json.load(file)
# Update the result with the loaded data (only if the file exists)
result.update(data)
return result
def save(data):
"""
This function will save the data. If there are some values missing, the
default will take place.
"""
# Again, create the filename to your settings file. Make sure this is the
# same as the load function uses.
home = os.path.expanduser('~')
filename = os.path.join(home, 'yoursettings.json')
# The home folder should always be exists. But we want to be sure. So check
# and create if not available.
if not os.path.isdir(home):
os.makedirs(home)
# First load the default values into a dummy.
dummy = dict(DEFAULTS)
# Update the default values the your data.
dummy.update(data)
# Now save the dummy with json.
with open(filename, 'w') as file:
json.dump(dummy, file)
if __name__ == '__main__':
# Some small examples
# Load the default values
data = load()
print(data)
# {'name': 'AxJu', 'foo': 'spam'}
# Change the values ​​and add some extras
data['foo'] = 'Hello'
data['age'] = 30
# Save the edited data
save(data)
# Load and show the new data
data = load()
print(data)
# {'name': 'AxJu', 'foo': 'Hello', 'age': 30}
@evandrix
Copy link

DEFUALTS DEFAULTS

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment