Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading a config file from operation system independent place in python

under Linux I put my configs in "~/.programname". Where should I place it in windows? What would be the recommendated way of opening the config file OS independent in python?

Thanks! Nathan

like image 473
Nathan Avatar asked Jul 14 '10 20:07

Nathan


People also ask

How do I open a config file in Python?

Just put the abc.py into the same directory as your script, or the directory where you open the interactive shell, and do import abc or from abc import * .

Which is the correct constant for a platform independent directory separator in Python?

In Windows you can use either \ or / as a directory separator.


2 Answers

On Windows, you store it in os.environ['APPDATA']. On Linux, however, it's now recommended to store config files in os.environ['XDG_CONFIG_HOME'], which defaults to ~/.config. So, for example, building on JAB's example:

if 'APPDATA' in os.environ:
    confighome = os.environ['APPDATA']
elif 'XDG_CONFIG_HOME' in os.environ:
    confighome = os.environ['XDG_CONFIG_HOME']
else:
    confighome = os.path.join(os.environ['HOME'], '.config')
configpath = os.path.join(confighome, 'programname')

The XDG base directory standard was created so that configuration could all be kept in one place without cluttering your home directory with dotfiles. Most new Linux apps support it.

like image 111
LeafStorm Avatar answered Nov 16 '22 00:11

LeafStorm


Some improvements over LeadStorm's great answer:

Code can be simpler using os.environ.get() and short-circuiting or:

configpath = os.path.join(
    os.environ.get('APPDATA') or
    os.environ.get('XDG_CONFIG_HOME') or
    os.path.join(os.environ['HOME'], '.config'),
    "programname"
)

Additionally, if you're willing to use the external libraries, xdg package can make things even easier on Linux and Mac:

import xdg.BaseDirectory as xdg
configpath = os.path.join(os.environ.get('APPDATA') or xdg.xdg_config_home,
                          "programname")

But this only solves part of your problem: you still need to create that directory if it does not exists, right?

On Windows, you're on your own. But on Linux and Mac, xdg.save_config_path() do os.path.join() for you, and create the directory with appropriate permissions, if needed, and return its path, all in a single step. Awesome!

if 'APPDATA' in os.environ:
    configpath = os.path.join(os.environ['APPDATA'], "programname")
    os.makedirs(configpath, exist_ok=True)
else:
    configpath = xdg.save_config_path("programname")
like image 21
MestreLion Avatar answered Nov 15 '22 22:11

MestreLion