Hi,
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
Hi,
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
Try:
os.path.expanduser('~/.programname')
On linux this will return:
>>> import os
>>> os.path.expanduser('~/.programname')
'/home/user/.programname'
On windows this will return:
>>> import os
>>> os.path.expanduser('~/.programname')
'C:\\Documents and Settings\\user/.programname'
Which is a little ugly, so you'll probably want to do this:
>>> import os
>>> os.path.join(os.path.expanduser('~'), '.programname')
'C:\\Documents and Settings\\user\\.programname'
EDIT: For what it's worth, the following apps on my Windows machine create their config folders in my Documents and Settings\user
folder:
EDIT 2: Oh wow, I just noticed I put /user/.programname
instead of /home/user/.programname
for the linux example. Fixed.
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')
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.