Home  >  Article  >  Backend Development  >  Python implements a method to obtain the current directory and the upper-level directory

Python implements a method to obtain the current directory and the upper-level directory

黄舟
黄舟Original
2017-10-12 11:04:202237browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn