How do I use a relative path in a Python module when the CWD has changed?

后端 未结 2 1847
忘掉有多难
忘掉有多难 2021-01-31 15:58

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 d

2条回答
  •  梦谈多话
    2021-01-31 16:40

    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()
    

提交回复
热议问题