I'm creating a program that allows you to do a whole ton of stuff, basically just built to make my life a little easier on my pc. However, the idea I had was that I could have a form of 'settings bar' where I could edit the settings (duh) of my program. The only problem I've ran into is that whenever I try to run the program all the variables will reset to their original positions. Now I could go through the painful and laborious process of changing a variable every time I wanted to change my settings, but is there a way I could edit another python file containing some variables and then change and save those variables?

8 Months
Discussion Span
Last Post by Gribouillis

There are many ways to do that, you can use the pickle module or the json module to persist data on disk.
A very simple solution is to use Raymond Hettinger's PersistentDict class. Download the code from here Click Here and save it under the name persistentdict.py.
You can then structure your program like this

from persistentdict import PersistentDict

def main(settings):
    ... # do things
    settings['foo'] = 'bar'

if __name__ == '__main__':
    with PersistentDict('mysettings.json', 'c', format='json') as settings:

With this code, your settings will be loaded from file mysettings.json when the program starts and will be stored in this file when the program exits. During the execution of the program, you can update the settings dictionary the way you want.

Edit: A json file can persist simple values, basically strings, numbers, lists or dictionary of such items, etc. In order to persist more complex python instances, the correct way to do it is to use a pickle file. It is a good rule to persist only simple data types when it is possible to do so.

Edit 2: A good idea is to give the absolute path of the settings file, otherwise the program will locate the file according to the current working directory at run time, which may vary between runs.

Edited by Gribouillis

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.