current position:Home>Get project root path and other paths in Python project

Get project root path and other paths in Python project

2022-05-15 05:35:23A small pit of goods

python in os.path Common modules

  • os.path.sep: Path separator linux I'll use this next time ’/’
  • os.path.altsep: root directory
  • os.path.curdir: Current directory
  • os.path.pardir: Parent directory
  • os.path.abspath(path): Absolute path
  • os.path.join(): Commonly used to link paths
  • os.path.split(path): hold path It is divided into two parts: directory and file , Return as a list

Get the project root path

#  Get the root path 
def getRootPath():
    #  Get file directory 
    curPath = os.path.abspath(os.path.dirname(__file__))
    #  Get the project root path , The content is the name of the current project 
    rootPath = curPath[:curPath.find(' Project name ')+len(' Project name ')]
    return  rootPath

Get other paths in the project

#  Get other paths from the root directory 
def getOtherPath(abspath:str):
	#  Called the above method to get the project root directory 
    rootPath = getRootPath()
    dataPath = os.path.abspath(rootPath + abspath)
    return dataPath

Get the current path of the file

Get the file path in the project , If you use pyinstaller After packing , You can use this method to find a temporary address .

#  Get the path , The path of the current file 
def resource_path(relative_path):
    #  whether Bundle Resource
    if getattr(sys, 'frozen', False):
        # running in a bundle
        base_path = sys._MEIPASS
        # running live
        base_path = os.path.abspath(".")
    return os.path.join(base_path, relative_path)

Get desktop path

def get_desktop_dir():
    """ @Description:  Get user desktop path  """
    return os.path.join(os.path.expanduser('~'),'Desktop')

If the error , Welcome to leave a message or send a private letter to inform . Learning together , thank you !

copyright notice
author[A small pit of goods],Please bring the original link to reprint, thank you.

Random recommended