Python - Get path of root project structure

后端 未结 16 1836
陌清茗
陌清茗 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:29

    Other answers advice to use a file in the top-level of the project. This is not necessary if you use pathlib.Path and parent (Python 3.4 and up). Consider the following directory structure where all files except README.md and utils.py have been omitted.

    project
    │   README.md
    |
    └───src
    │   │   utils.py
    |   |   ...
    |   ...
    

    In utils.py we define the following function.

    from pathlib import Path
    
    def get_project_root() -> Path:
        return Path(__file__).parent.parent
    

    In any module in the project we can now get the project root as follows.

    from src.utils import get_project_root
    
    root = get_project_root()
    

    Benefits: Any module which calls get_project_root can be moved without changing program behavior. Only when the module utils.py is moved we have to update get_project_root and the imports (refactoring tools can be used to automate this).

提交回复
热议问题