繁体   English   中英

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

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

我有以下目录结构:

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

PythonProject是我的主目录,在source目录中我有一些 python 脚本。 script.py我想访问configs中存在的配置文件。 在这里,我不想提及完整路径,例如E:\<somepath>\PythonProject\configs\config.json a 我将把它部署到我不知道路径的系统上。 所以我决定用 go

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

但这给了我到源目录的路径,即E:\<somepath>\PythonProject\source我只想要E:\<somepath>\PythonProject以便我以后可以添加configs\config.json来访问配置的路径文件。

我怎样才能做到这一点。 谢谢

单程:

import os 

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

print(config_file_path)

或(您需要 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)

第三种方式:

from os.path import dirname as up

dir = up(up(__file__))

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

使用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)

你可以用 os 模块来做到这一点:

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

您可以使用pathlib模块:

(如果没有,请使用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)

这使:

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

(来自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