In this post, we will see how to resolve How to tell python to use same directory for file
Question:I need this python project to be useable for multiple users after downloading it from git, but I’m having a problem generalizing paths. I have it set to use absolute paths in my version, but that will break for others, and if I’m using a file in the same directory as the module, python can’t find it if I use the relative path (i.e.,
with open('foo.txt') as f).
I settled on a text file called properties.txt in the project directory, and a module that reads it into a dict. Right now it just has one line,
MAIN_DIR=/my/home/directory. The problem is circular though. I can’t use a relative path to read that text file either.
I’m confident this solution is overengineered. There’s got to be a way to get around that, or to get around the problem with relative paths in the first place?
Best Answer:There are a few different approaches, depending on your needs and constraints.
One option is to use some “standard” location. For instance,
~/.config/myprog/foo.confis a standardized way to locate per-user configuration files.
Another option is to have an environment variable, that your user must set. Perhaps with fallback to a “default” path of some sort (like above).
Another option, for something like a script, is to use something like
cd "$(dirname "$0")"/..— that’s Bash script, but you get the idea. In Python you’d use
sys.argv. This makes the current working directory the one in which the script is located. You can use relative paths from then onward.
The question mentioned in your comments has a good general overview: https://stackoverflow.com/a/58941536/567650
It depends a bit on how fancy your build/packaging setup is. If you’re just sending a file or three, then the above “change the current directory” approach is common and would probably work okay, but would fall under the “Bad way #1:” heading, in the other answer I linked.
If you have better answer, please add a comment about this, thank you!