On 22/05/2025 23:45, Mats Wichmann wrote:
On 5/22/25 13:59, Michael F. Stemper via Python-list wrote:
I recently wrote a program to do some record-keeping for me. I found
myself hard-coding a bunch of different values into it. This didn't
seem right, so I made my first use of configparser.ConfigParser().
Created the configuration file and everything is working fine.
However, I wrote it based on the assumption that the program is
running in the directory where the config file is stored, and has
a specific name. I started having some second thoughts here.
I thought about putting the location of the configuration file in
the configuration file, but that seemed like a non-starter.[1]
Should I specify the location of the config file with a command-line
option, or is requiring the program to be executed in the directory
containing the configuration file considered acceptable practice?
Eh, there are so many context-dependent practices that it's largely
impossible to identify something to call a "best practice" these days.
I'm going to make a couple of comments, but there's more to consider
than just these thoughts.
There's a sort-of-standard package called platformdirs (a successor to
appdirs) which tries to tell you where to put things in a
platform-independent way.
https://pypi.org/project/platformdirs/
https://pypi.org/project/appdirs/
This works nicely if you're building something to distribute, and you
want to have a system-neutral way to access a config file. For
personal stuff, that may be overkill. If it's only for you, just do
what works. Enhancement: have a default location for the config file
hard-coded, but provide a cmdline option to give an alternative.
Mats is absolutely correct that there is no "one size fits all" solution.
However one solution that might or might not suit you (at least on
WIndows; I hope it's applicable to Unix) is to look at sys.path and
search for your configuration file in every directory it lists until you
find it (or give an error message if it
isn't). Alternatively look at the PATH envronment variable, which
contains a list of directories separated by semicolons and which you can
access as os.environ['PATH'] .
Best wishes,
Rob Cliffe
--
https://mail.python.org/mailman3//lists/python-list.python.org