如何在python

我具有以下目录结构:

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(文件))

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

我该怎么做。谢谢

pklimi 回答:如何在python

一种方式:

import os 

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

print(config_file_path)

或(您需要点安装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')
,

使用// theFileYouDeclaredTheCustomConfigIn.ts declare module 'axios' { export interface AxiosRequestConfig { handlerEnabled: boolean; } }

pathlib
,

您可以仅使用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?https://stackoverflow.com/users/4172/kender

本文链接:https://www.f2er.com/3133153.html

大家都在问