Loading a config file from operation system independent place in python

python' config file
config path python
flask config file example
python pathlib list files
python pathlib copy file
flask configuration best practices
python pathlib examples
python pathlib to string

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

config-path · PyPI, a library to work with paths to config folders and files in an OS independent way. Python library to work out witch path to use for configuration folders and files from config_path import ConfigPath conf_path = ConfigPath(  Let’s take a very basic configuration file that looks like this: [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User = hg [topsecret.server.com] Port = 50022 ForwardX11 = no. The structure of INI files is described in the following section.

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.

Installing Python Modules (Legacy version), independently covers all of the relevant information currently included here. On Unix (and Mac OS X, which is also Unix-based), it also depends on Thus, you can put these options into your Distutils config file (see section You can determine the path by importing the sys module and printing the value of sys.path . Writing and Reading config files in Python. I’m sure you must be aware about the importance of configuration files.Config files help creating the initial settings for any project, they help avoiding the hardcoded data.

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")

Configuration Handling, Independent of how you load your config, there is a config object available which holds This is the place where Flask itself puts certain configuration values and also python -c 'import os; print(os.urandom(16))' b'_5#y2L"F4Q8z\n\xec]/' When serving files, set the X-Sendfile header instead of serving the data with Flask. File Endings give the user and the system an indicator about the content of a file. Reasonable file endings for configuration files are *config.py for Python files *.yaml or *.yml if the configuration is done in YAML format *.json for configuration files written in JSON format *.cfg or *.conf to indicate that it is a configuration file

Generally, configuration and data files for programs on Windows go in the %APPDATA% directory (or are supposed to), usually in a subdirectory with the name of the program. "%APPDATA%", of course, is just an environment variable that maps to the current user's Application Data folder. I don't know if it exists on Linux (though I assume it doesn't), so to do it across 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')

Python 3's pathlib Module: Taming the File System – Real Python, How to effectively work with file system paths in Python 3 using the new import glob import os import shutil for file_name in glob.glob('*.txt'): new_path It gathers the necessary functionality in one place and makes it available The forward slash operator is used independently of the actual path separator on the platform:. Previous way should import the configuration .py file from specific file which need to use configuration, so, the config file must be located on import-able path. But, In this approach, the config file does not have to located on import-able path and can even be located on other repository. The principle is so simple.

Python Advanced: Python and the Shell, The os module allows platform independent programming by providing Most Python scripts dealing with the operating system need to know the postion in the file system. import os def getch(): os.system("bash -c \"read -n 1\"") getch() '.​profile', '.config', '.esd_auth', '.viminfo', '.sudo_as_admin_successful', 'mbox',  When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed so that the resources that are tied with the file are freed. Hence, in Python, a file operation takes place in the following order: Open a file; Read or write (perform operation) Close the file

Best Practice: Working with Paths in Python - Part 2, Such errors can occur whenever users manage the path in config files, far from the This handles file and folder functions of Python's os module with an import os path = "C:/Users/sselt/Documents/blog_demo/" os.path.isdir(path) In addition to other advantages, the code is also independent of the operating system. In this tutorial we will be learning about how to work with config file and read from config file. Check out the Free Course on- Learn Julia Fundamentals htt

Get File Size, Remove Directory, ${path}, recursive=${TRUE}, # Python True is true. Append To Environment Variable · Append To File · Copy Directory · Copy File · Copy Files · Count Directories In No other configuration parameters are accepted. Line breaks in content are converted to platform independent form. The following are code examples for showing how to use config.load().They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Comments
  • "Which is a little ugly[.]" Works just fine, though.
  • This is a truly cross-platform answer!
  • The os.makedirs(configpath, exist_ok=True) just works under py3. py2: if not os.path.exists(configpath): os.makedirs(configpath)
  • @greeeeeeen: For Py2, I'd recommend a try/except block around os.makedirs to avoid a race condition, in true pythonic EAFP spirit
  • I think this is no EAFP case... if talking about pythonicity, I think, the if construction is following the "explicit is better then implicit" guide.
  • @greeeeeeen: testing if dir exists and then creating it is LBYL pattern and can lead to race conditions if the directory is created after the if and before os.makedirs(). Very unlikely, but it's good practice to avoid racy patterns whenever we can. And, in this case, EAFP is also faster. As for "explicitness", IMHO directly trying to create and handling any errors is even more explicit
  • Good point. So best would be to adapt the os.makedirs implementation from python 3 in that case. There they use a try-except block as you suggested. github.com/python/cpython/blob/…