Python - Get path of root project structure

后端 未结 16 1835
陌清茗
陌清茗 2020-12-04 08:03

I\'ve got a python project with a configuration file in the project root. The configuration file needs to be accessed in a few different files throughout the project.

16条回答
  •  我在风中等你
    2020-12-04 08:25

    At the time of writing, none of the other solutions are very self-contained. They depend either on an environment variable or the position of the module in the package structure. The top answer with the ‘Django’ solution falls victim to the latter by requiring a relative import. It also has the disadvantage of having to modify a module at the top level.

    This should be the correct approach for finding the directory path of the top-level package:

    import sys
    import os
    
    root_name, _, _ = __name__.partition('.')
    root_module = sys.modules[root_name]
    root_dir = os.path.dirname(root_module.__file__)
    
    config_path = os.path.join(root_dir, 'configuration.conf')
    

    It works by taking the first component in the dotted string contained in __name__ and using it as a key in sys.modules which returns the module object of the top-level package. Its __file__ attribute contains the path we want after trimming off /__init__.py using os.path.dirname().

    This solution is self-contained. It works anywhere in any module of the package, including in the top-level __init__.py file.

提交回复
热议问题