Michał Dobranowski
Michał Dobranowski

Reputation: 33

Store user settings in Python script

I created a Python package that is actually a command line interface. Everything works fine, but I would like to be able to store simple user settings (a few values) in some file (json, yaml, or whatever). Handling such files itself is not a problem, but I don't know where I could store them. My program can be installed using pip install https://github.com/repo and works fully off-line.

It seems that Python does not allow me to store settings files in the same folder, where the compiled program itself is located (Programs\Python\Python38\Scripts) which makes sense, but I don't know how to do it any other way.

Upvotes: 1

Views: 869

Answers (1)

Michał Dobranowski
Michał Dobranowski

Reputation: 33

Inspired by the comments under the question, I searched a little bit more and found the answer to my problem.

I store my settings file in C:\users\me\appdata\local\programs\python\python38\lib\site-packages\my_package\config.json which can be accessed with

os.path.join(os.path.dirname(os.path.abspath(__file__)), 'config.json')

I haven't tested this on Linux or macOS yet, but I think it will work.

EDIT: Unfortunately it does not work on Linux without sudo. For this reason, I used the following:

os.path.join(os.path.expanduser("~"), '.my_package_name', 'config.json')

Upvotes: 1

Related Questions