Skip to content Skip to sidebar Skip to footer

How Do I Use A Relative Path In A Python Module When The CWD Has Changed?

I have a Python module which uses some resources in a subdirectory of the module directory. After searching around on stack overflow and finding related answers, I managed to dire

Solution 1:

Store the absolute path to the module directory at the very beginning of the module:

package_directory = os.path.dirname(os.path.abspath(__file__))

Afterwards, load your resources based on this package_directory:

font_file = os.path.join(package_directory, 'fonts', 'myfont.ttf')

And after all, do not modify of process-wide resources like the current working directory. There is never a real need to change the working directory in a well-written program, consequently avoid os.chdir().


Solution 2:

Building on lunaryorn's answer, I keep a function at the top of my modules in which I have to build multiple paths. This saves me repeated typing of joins.

def package_path(*paths, package_directory=os.path.dirname(os.path.abspath(__file__))):
    return os.path.join(package_directory, *paths)

To build the path, call it like this:

font_file = package_path('fonts', 'myfont.ttf')

Or if you just need the package directory:

package_directory = package_path()

Post a Comment for "How Do I Use A Relative Path In A Python Module When The CWD Has Changed?"