Skip to content

Instantly share code, notes, and snippets.

@gesquive
Last active August 29, 2015 14:14
Show Gist options
  • Save gesquive/b842c74acc57c9259f92 to your computer and use it in GitHub Desktop.
Save gesquive/b842c74acc57c9259f92 to your computer and use it in GitHub Desktop.
Code snippet to get the config location based on the XDG Base Directory Specification.
import os
def get_config_path(project_name=None, config_name=None):
'''
Gets the config location based on the XDG Base Directory Specification.
If no config is found, the home directory based path is returned.
'''
if not project_name:
project_name = os.path.basename(__file__).split('.')[0]
if not config_name:
config_name = "{}.conf".format(project_name)
locations = [
os.path.join(os.curdir, config_name),
os.path.join(os.path.expanduser('~'), '.config', project_name, config_name),
os.path.join('/etc', project_name, config_name),
os.environ.get("{}_CONF".format(project_name)),
]
for path in locations:
if path and os.path.exists(path) and os.path.isfile(path):
return path
return locations[1]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment