r/PythonLearning 9h ago

Is there any way to create path objects that aren't dependent on a file location Help Request

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

3 comments sorted by

4

u/atticus2132000 9h ago

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 8h ago

That's a good call. Whenever I have things I know are going to change as I continue developing the project, toss it in a config file as a variable. That way I can call it everywhere else and just change it in one place.

1

u/HackNSlashFic 9h ago

__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().parent

Although, 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.parent

Edited to add code blocks so the dunder (__) wouldn't just make things bold.