Search code examples
pythonregistrypreferencespersistent

How to store variables/preferences in Python for later use


I'm working on a program in Python for Windows, and would like to save variables and user preferences so that I can recall them even after the program has been terminated and restarted.

Is there an ideal way to do this on Windows machines? Would _winreg and the Windows registry be suited for this task? Or do I need to create some sort of database of my own?


Solution

  • You're usually going to want to store it in a configuration folder in the "home" folder. That's easy on *nix systems, more difficult in windows, because you actually need to get the "application data" directory. This usually works for me:

    import os
    if os.name != "posix":
        from win32com.shell import shellcon, shell
        homedir = "{}\\".format(shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, 0, 0))
    else:
        homedir = "{}/".format(os.path.expanduser("~"))
    

    After you have the homedirectory, you should create a folder named after your project:

    if not os.path.isdir("{0}.{1}".format(homedir,projectname)):
        os.mkdir("{0}.{1}".format(homedir,projectname))
    

    Then you can make a config file in that folder and write your options to it in the format of your choosing (my personal favorite is in an XML).