我有以下目录结构:
E:<somepath>PythonProject
-> logs
-> configs
-> source
-> script.py
PythonProject
是我的主目录,在source
目录中我有一些python脚本。我想从script.py
访问configs
中的配置文件。在这里,我不想提及像E:<somepath>PythonProjectconfigsconfig.json
这样的完整路径,我将把它部署到一个我不知道路径的系统中。所以我决定选择
config_file_path=os.path.join(os.path.dirname(文件((
但这给了我源目录的路径,即E:<somepath>PythonProjectsource
,我只想要E:<somepath>PythonProject
,这样我以后就可以添加configsconfig.json
来访问配置文件的路径。
我该怎么做。感谢
单向:
import os
config_file_path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'configsconfig.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, 'configsconfig.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)
只需操作系统模块即可完成:
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?byhttps://stackoverflow.com/users/4172/kender)