Loading a configuration file from an operating system independent location in python

under Linux I put my configs in "~ / .programname". Where should I put it in the windows? What would be the recommended way to open a standalone configuration file in python?

Thanks! Nathan

+4
source share
3 answers

Try:

os.path.expanduser('~/.programname') 

On linux, this will return:

 >>> import os >>> os.path.expanduser('~/.programname') '/home/user/.programname' 

In windows, this will return:

 >>> import os >>> os.path.expanduser('~/.programname') 'C:\\Documents and Settings\\user/.programname' 

This is a little ugly, so you probably want to do this:

 >>> import os >>> os.path.join(os.path.expanduser('~'), '.programname') 'C:\\Documents and Settings\\user\\.programname' 

EDIT: for what, the following applications on my Windows computer create their own configuration folders in my Documents and Settings\user folder:

  • Android
  • AgroUML
  • Gimp
  • Ipython

EDIT 2: Oh, I just noticed that instead of /user/.programname , /home/user/.programname was placed /user/.programname . Fixed.

+4
source

On Windows, you save it to os.environ['APPDATA'] . However, on Linux it is now recommended that you store configuration files in os.environ['XDG_CONFIG_HOME'] , by default ~/.config . So, for example, using the JAB 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 standard base directory was created so that the configuration could be saved in one place without cluttering your home directory with dotfiles. Most new Linux applications support it.

+7
source

Typically, the configuration and data files for programs on Windows are in the% APPDATA% directory (or assumed), usually in a subdirectory with the name of the program. "% APPDATA%", of course, is just an environment variable that maps to the current user data folder of the application. I do not know if it exists on Linux (although I assume that it is not), so do it on different platforms (Windows / Linux / MacOS) ...

 import os if 'APPDATA' in os.environ.keys(): envar = 'APPDATA' else: envar = 'HOME' configpath = os.path.join(os.environ[envar], '.programname') 
0
source

Source: https://habr.com/ru/post/1315716/


All Articles