如何在python中获取父目录的路径
我有以下目录结构:如何在python中获取父目录的路径,python,directory,path,Python,Directory,Path,我有以下目录结构: E:\<somepath>\PythonProject -> logs -> configs -> source -> script.py PythonProject是我的主目录,在源目录中我有一些python脚本。我想从script
E:\<somepath>\PythonProject
-> logs
-> configs
-> source
-> script.py
PythonProject是我的主目录,在源目录中我有一些python脚本。我想从script.py访问configs中的配置文件。这里我不想提及完整的路径,如E:\\PythonProject\configs\config.json,我将把它部署到一个我不知道路径的系统中。所以我决定和你一起去
config_file_path=os.path.joinos.path.dirnamefile
但这给了我到源目录的路径,即E:\\PythonProject\source,我只需要E:\\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 os.path import dirname as up
dir = up(up(__file__))
config_file_path = os.path.join(dir, 'configs\config.json')
使用路径库:
从pathlib导入路径
p=此处的路径
关于这个文件的信息太多了
打印p.name、p.parent、p.parts[-2]
printp.resolve
印染茎
您只需使用操作系统模块即可:
import os
direct = os.getcwd().replace("source", "config")
您可以使用pathlib模块:
如果没有,请在终端中使用pip安装pathlib
从pathlib导入路径
path=path//PythonProject/configs/config.json
printpath.parents[1]
path=path/here/your/path/file.txt
printpath.parent
printpath.parent.parent
printpath.parent.parent.parent
printpath.parent.parent.parent.parent.parent
printpath.parent.parent.parent.parent.parent.parent
其中:
/<somepath>/PythonProject
/here/your/path
/here/your
/here
/
/
这是否回答了您的问题?为什么不使用循环呢?为什么不让父母给他们所有的呢?为什么要引用另一个问题而不是将此问题标记为重复问题?谢谢@ofer sadan。是的。我还需要声誉达到15,所以我的选票很重要。
/<somepath>/PythonProject
/here/your/path
/here/your
/here
/
/