Python : How to access file from different directory

后端 未结 3 1704
梦如初夏
梦如初夏 2020-12-07 03:22

I have the following project structure

SampleProject
     com
       python
          example
             source
                utils
                   Co         


        
3条回答
  •  感动是毒
    2020-12-07 03:54

    You can use the pathlib package in Python 3.0+

    This gets the path to any file contained in the SampleProject folder across different platforms.

    from pathlib import Path
    def get_file(path):
        """
        returns the absolute path of a file
        :var
        str path
            the file path within the working dir
        :returns
        PureWindowsPath or PurePosixPath object
            type depends on the operating system in use
        """
        def get_project_root() -> Path:
        """Returns project root folder."""
        return Path(__file__).parent.parent
    
        return get_project_root().joinpath(path)
    

    Then simply call the function with the file_path as an argument:

    filePath = get_file('com/python/example/source/utils/configManager.py')
    

    And then the usual procedure:

    while open(filePath) as f:
        
    

提交回复
热议问题