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
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 * .
In Windows you can use either \ or / as a directory separator.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With