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

后端 未结 2 1849
忘掉有多难
忘掉有多难 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:37

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

提交回复
热议问题