简体   繁体   English

python中如何获取父目录的路径

[英]How to get the path of the parent directory in python

I have below directory structure:我有以下目录结构:

E:\<somepath>\PythonProject
                        -> logs
                        -> configs
                        -> source
                                -> script.py

PythonProject is my main directory and inside the source dir I have some python script. PythonProject是我的主目录,在source目录中我有一些 python 脚本。 From the script.py I want to access the config file present in configs .script.py我想访问configs中存在的配置文件。 Here I don't want to mention the full path like E:\<somepath>\PythonProject\configs\config.json a I will be deploying this to a system for which I am not aware of the path.在这里,我不想提及完整路径,例如E:\<somepath>\PythonProject\configs\config.json a 我将把它部署到我不知道路径的系统上。 So I decided to go with所以我决定用 go

config_file_path = os.path.join(os.path.dirname( file )) config_file_path = os.path.join(os.path.dirname( file ))

But this gives me path to the source dir which is E:\<somepath>\PythonProject\source and I just want E:\<somepath>\PythonProject so that I can later add configs\config.json to access the path to config file.但这给了我到源目录的路径,即E:\<somepath>\PythonProject\source我只想要E:\<somepath>\PythonProject以便我以后可以添加configs\config.json来访问配置的路径文件。

How can I do this.我怎样才能做到这一点。 Thanks谢谢

one way:单程:

import os 

config_file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'configs\config.json')

print(config_file_path)

or (you will need to pip install pathlib ):或(您需要 pip 安装pathlib ):

from pathlib import Path

dir = Path(__file__).parents[1]
config_file_path = os.path.join(dir, 'configs/config.json')

print(config_file_path)

third way:第三种方式:

from os.path import dirname as up

dir = up(up(__file__))

config_file_path = os.path.join(dir, 'configs\config.json')

Use pathlib :使用pathlib

from pathlib import Path

p = Path(path_here)

# so much information about the file
print(p.name, p.parent, p.parts[-2])
print(p.resolve())
print(p.stem)

You can do it with just os module:你可以用 os 模块来做到这一点:

import os
direct = os.getcwd().replace("source", "config")

You can use the pathlib module:您可以使用pathlib模块:

(If you dont have it, use pip install pathlib in Terminal.) (如果没有,请使用pip install pathlib 。)

from pathlib import Path
path = Path("/<somepath>/PythonProject/configs/config.json")
print(path.parents[1])

path = Path("/here/your/path/file.txt")
print(path.parent)
print(path.parent.parent)
print(path.parent.parent.parent)
print(path.parent.parent.parent.parent)
print(path.parent.parent.parent.parent.parent)

which gives:这使:

/<somepath>/PythonProject
/here/your/path
/here/your
/here
/
/

(from How do I get the parent directory in Python? by https://stackoverflow.com/users/4172/kender ) (来自How do I get the parent directory in Python? by https://stackoverflow.com/users/4172/kender

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

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