簡體   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