如何在Python中获取父目录的路径

3
我有以下目录结构:
E:\<somepath>\PythonProject
                        -> logs
                        -> configs
                        -> source
                                -> script.py

PythonProject 是我的主目录,在 source 目录中有一些 Python 脚本。 在 script.py 中,我想访问位于 configs 中的配置文件。我不想像这样提及完整路径:E:\<somepath>\PythonProject\configs\config.json,因为我将把它部署到一个我不知道路径的系统上。所以我决定使用:

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

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

我该如何做呢?谢谢。


2
这个回答解决了你的问题吗?如何在Python中获取父目录? - PythonLearner
4个回答

7

一种方法:

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')

1
像“up up”方式哈哈 - Franva

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


2
您可以使用 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
/
/

(来自如何在Python中获取父目录?,作者为https://stackoverflow.com/users/4172/kender

为什么不使用循环?为什么不使用parents来获取它们所有的内容?为什么要引用另一个问题,而不是将此问题标记为重复? - Ofer Sadan
感谢@ofer-sadan。我已经做了。 我还需要达到15的声望,这样我的投票才有用。 - Ornataweaver

2
您可以仅使用os模块完成此操作:
import os
direct = os.getcwd().replace("source", "config")

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接