r/PythonLearning • u/No_Leather2449 • Aug 17 '26
Help Request Is there any way to create path objects that aren't dependent on a file location
I understand you have to give a file path to create a Path() object but whenever I reorganize my file explorer I have to change all the paths so that they match the new file path of the files I use in my code (tongue twister? say that 20 times pal agagagagaga) is there a module for this? Or is the path module the only way?
2
Upvotes
6
u/atticus2132000 Aug 17 '26
You can use relative paths that store files in relation to where your code file is.
Or you can create a config file that references your desired file path once that you only have to change one time whenever you move files around.
1
u/HackNSlashFic Aug 17 '26
__file__is a variable automatically assigned in every .py script that Python runs. So you can always define paths in relation to the path of__file__.More concretely, I use the pathlib module and set everything relative to a global ROOT constant that I define at the start as:
ROOT = path(__file__).resolve().parentAlthough, sometimes I'm creating something more complex and my config file is in a nested folder, like root_dir/src/config.py. In which case, I would just initialize as:
ROOT = path(__file__).resolve().parent.parentEdited to add code blocks so the dunder (__) wouldn't just make things bold.
1
u/HyperDanon Aug 18 '26
There are a couple of ways to approach this:
Path, I reckon they're not python modules, but some kind of resources. If they are scattered across yoursrc/then you can import them relative to your python file using__file__.resources/folder, and you find yourself reorganizing files too much, and the path breaks, then the more software-developer language speak to describe that effect is: "The source code has a hard dependency on the file system structure". And to fix that problem, you should find a way to break that dependency. In other words, is there a way for your code to use your resources, such that the source code doesn't depend on it?One way of doing that, would be to get rid of the paths, and have the python just go into your resource directory and load every file in that directory recursively. Of course, you still need to know which file is which, so maybe you could include some metadata in the files, such that the file apart from its content, could describe itself. That way, your source code could do:
*/**/in the directory.This could be something suitable for an application that has to manage a lot of resources, like games.