簡體   English   中英

python:如何獲取父目錄的絕對路徑

[英]python : how to get absolute path for a parent dir

我在a/b/c/d/e/f/x.xml位置有一個文件。 我需要找到目錄d的絕對路徑,即與目錄名d匹配的層次結構中的父目錄。

我可以獲取文件名的當前目錄為os.path.abspath(__file__) 我已經看到pathlibglob的文檔,但無法弄清楚我將如何使用它們。

有人可以幫忙嗎

編輯:

多虧了以下所有答案,我的專才才行

os.path.join(*list(itertools.takewhile(lambda x: x != 'd', pathlib.PurePath(os.getcwd()).parts)))

我還需要在其后面附加實際的目錄名稱,即輸出應為a/b/c/d 下面是一個丑陋的解決方案(兩次使用os.path.join)。 有人可以修復它(通過將元素添加到迭代器或列表中的一行:)

os.path.join(os.path.join(*list(itertools.takewhile(lambda x: x != 'd', pathlib.PurePath(os.getcwd()).parts))),"d")

您可以在__file__的絕對路徑上使用dirname來獲取abspath完整路徑

os.path.dirname(os.path.abspath(__file__))

>>> import pathlib
>>> p = pathlib.PurePath('a/b/c/d/e/f/x.xml')
>>> p.parts
('a', 'b', 'c', 'd', 'f', 'x.xml')

然后,您可以提取路徑的任何部分。 如果要獲取d文件夾:

import itertools
res = '/'.join(itertools.takewhile(lambda x: x != 'd', p.parts))

您可以使用pathlibPath.resolve()Path.parents

from pathlib import Path

path = Path("a/b/c/d/e/f/x.xml").resolve()

for parent in path.parents:
    if parent.name == "d":  # if the final component is "d", the dir is found
        print(parent)
        break

使用正則表達式並剪切:

import re
import os
mydir_regexp = re.compile('dirname')
abs_path = os.path.abspath(__file__)
s = re.search(mydir_regexp, abs_path)

my_match = abs_path[:abs_path.index(s.group())+len(s.group())]

假設您當前目錄中有一個文件,則可以使用abspath獲取它的絕對路徑(從根目錄開始):

path = os.path.abspath(filename)

Thes神奇的詞是os.path.split ,它將路徑名分為最后一個部分和頭部(前面的所有內容)。 因此,要獲取d之前發生的事情的絕對路徑,只需迭代組件即可:

def findinit(path, comp):
    while (len(path) > 1):
        t = os.path.split(path)
        if t[1] == comp:
            return t[0]
        path = t[0]
    return None

您可以控制findinit('/a/b/c/d/e/f/x.xml')給出預期的/a/b/c


或者,如果要使用pathlib模塊,則可以在parts搜索特定組件:

def findinit(path, comp):
    p = pathlib.PurePath(path)
    i = p.parts.index(comp)
    if i != -1:
        return pathlib.PurePath(*p.parts[:i])
    return None

我終於找到了單線:

os.path.join(*list(itertools.takewhile(lambda x: x != 'd', pathlib.PurePath(os.getcwd()).parts)),"d")

如果沒有其他答案,這是不可能的。 非常感謝。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM