Home > Article > Backend Development > Python implements a method to obtain the current directory and the upper-level directory
This article mainly introduces the implementation method of obtaining the current directory and upper-level directory in python. Friends who need it can refer to
to obtain the path of the current file:
from os import path d = path.dirname(__file__) #返回当前文件所在的目录 # __file__ 为当前文件, 若果在ide中运行此行会报错,可改为 #d = path.dirname('.')
Get the parent directory of a path:
parent_path = os.path.dirname(d) #获得d所在的目录,即d的父级目录 parent_path = os.path.dirname(parent_path) ##获得parent_path所在的目录即parent_path的父级目录
Get the canonical absolute path:
abspath = path.abspath(d) #返回d所在目录规范的绝对路径
Summarize
The above is the detailed content of Python implements a method to obtain the current directory and the upper-level directory. For more information, please follow other related articles on the PHP Chinese website!