'Is it possible to create a dynamic path within a Python script?

The idea is, I have various directories with a random number of files in each directory. Currently, I have a working script that I can copy into each dir and run and it will rename each file in that dir to my liking.

Here is my pain point: If I were to copy this script to another dir, I would have to change the path within my script so it renames the files in the correct directory. If I do not change the path in my script, it will rename files from the previous dir, which is not my intention.

My question is: can I create a dynamic reference in my script so that the script will update its own path so it will rename the files in the intended dir? This way, I will only have to copy the script to the new dir and run it.

I am using os.rename() to rename my files.

os.rename is using a path that has a prefixed 'r'. This is an example of how I am doing this with os.rename():

python
folder = r'M:\Python Projects\Rename Files\Repo\\'
source = folder + file_name 
destination = folder + d + " " + lookup_table[lookup_val] + ".pdf"
os.rename(source, destination)

I would like my folder variable to be dynamic. So for example when I copy the script over to another dir, folder would be the path of the current dir.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source