Like everyone else, I wrote a lot of programs which saved config files as dotfiles in the user's home directory like ~/.my-program-name and now everyone's home directory has dozens of these.
Then I read this article.
Great was my embarrasment to discover that there was a neat little specification for data, config and cache directories in Linux that prevents this problem, and that I was not using it:
So I implemented a small and simple Python API as a single file, cfgs.py.
It works on all versions of Python from 2.7 to 3.7, has complete test coverage, and all the functionality is reachable from a single class, cfgs.App
Create a cfgs.App for your application, project, or script which handles finding, reading and writing your data and config files, and managing your cache directories.
You can either use pip:
pip install cfgsOr if you don't like dependencies (and who does?), you can drop the source file cgfs.py right into your project.
importcfgsapp=cfgs.App('my-project') print(app.xdg.XDG_CACHE_HOME) # /home/tom/.cacheapp.xdg.XDG_CONFIG_DIRS# /etc/xdgwithapp.config.open() asf: f.contents.update(name='oliver', species='dog') f.contents['description'] ={'size': 'S', 'fur': 'brown'} print(f.filename) # /home/tom/.config/my-project/my-project.json# Later:withapp.config.open() asf: print(f.contents['name']) # oliverprint(f.as_dict()) #{'name': 'oliver', 'species': 'dog',# 'description':{'size': 'S', 'fur': 'brown'}importcfgscache_size=0x10000000app=cfgs.App('my-project') directory=app.cache.directory(cache_size=cache_size) withdirectory.open('cache') asf: f.write('cache data') # TODO: rewrite cache or add features.If you already have code to handle your config, data and cache files, then you can just use cgfs to get the XDG variables
fromcfgsimportXDGxdg=XDG() config_dir=xdg.XDG_CONFIG_HOME# Your code here - eg:my_config_file=os.path.join(config_dir, 'my-file.json') withopen(my_config_file) asf: legacy_write_my_file(f)cfgs automatically handles data and config files, and independently, cache directories.
API documentation is here.