简体   繁体   English

如何在python中获取当前.py文件的更高级别目录的路径?

[英]How can I get the path of the higher level directory of the current .py file in python?

Say there's a directory hierarchy like this: .../A/B/main.py . 假设存在这样的目录层次结构: .../A/B/main.py

main.py is the file being executed, and I need to get the full path of folder A , how can I do that? main.py是正在执行的文件,我需要获取文件夹A的完整路径,该怎么办?

Use the os module: 使用os模块:

import os
a_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

To get the path of the current directory, you can use: 要获取当前目录的路径,可以使用:

import os
print os.path.realpath('.')

since . 从此. represents the current directory in the file system. 表示文件系统中的当前目录。 So to get the path of the higher level directory, just replace . 因此,要获取更高级别目录的路径,只需替换即可. with .. , which represents parent directory ..代表父目录

import os
print os.path.realpath('..')

You can also use the os.getcwd() method to get the current working directory and then get its parent directory with the .. representation. 您也可以使用os.getcwd()方法获取当前的工作目录,然后使用..表示形式获取其父目录。

In Python 3: 在Python 3中:

from pathlib import Path

mypath = Path().absolute().parent.parent  # each '.parent' goes one level up - vary as required
print(mypath)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM