[英]python : how to get absolute path for a parent dir
I have a file at location a/b/c/d/e/f/x.xml
. 我在
a/b/c/d/e/f/x.xml
位置有一个文件。 i need to find the absolute path of the the dir d
, ie a parent dir up the hierarchy that matches the dir name d
. 我需要找到目录
d
的绝对路径,即与目录名d
匹配的层次结构中的父目录。
I can obtain the filename's current dir as os.path.abspath(__file__)
. 我可以获取文件名的当前目录为
os.path.abspath(__file__)
。 i have see the documentation for pathlib and glob , but am unable to figure out how would i use them. 我已经看到pathlib和glob的文档,但无法弄清楚我将如何使用它们。
Can someone help 有人可以帮忙吗
EDIT: 编辑:
Thanks to all the answers below, I have gotten to a one liner 多亏了以下所有答案,我的专才才行
os.path.join(*list(itertools.takewhile(lambda x: x != 'd', pathlib.PurePath(os.getcwd()).parts)))
I also need to append the actual dir name to it, ie, the output should be a/b/c/d
. 我还需要在其后面附加实际的目录名称,即输出应为
a/b/c/d
。 An ugly solution is below (uses os.path.join twice). 下面是一个丑陋的解决方案(两次使用os.path.join)。 Can someone fix it (by adding an element to the iterator or to the list in one line :)
有人可以修复它(通过将元素添加到迭代器或列表中的一行:)
os.path.join(os.path.join(*list(itertools.takewhile(lambda x: x != 'd', pathlib.PurePath(os.getcwd()).parts))),"d")
You use can use dirname
on abspath
of __file__
to get the full path of the x.xml: 您可以在
__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')
Then you can extract any part of your path. 然后,您可以提取路径的任何部分。 If you want to get the
d
folder: 如果要获取
d
文件夹:
import itertools
res = '/'.join(itertools.takewhile(lambda x: x != 'd', p.parts))
You can use pathlib
's Path.resolve()
and Path.parents
: 您可以使用
pathlib
的Path.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
Use regexp and cut: 使用正则表达式并剪切:
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())]
Assuming you have a file in your current dir, you can get it absolute path (starting at root) with abspath
: 假设您当前目录中有一个文件,则可以使用
abspath
获取它的绝对路径(从根目录开始):
path = os.path.abspath(filename)
Thes the magic word is os.path.split
that splits a pathname into the last component and the head (everything in front of it). Thes神奇的词是
os.path.split
,它将路径名分为最后一个部分和头部(前面的所有内容)。 So to get the absolute path of what comes before d
just iterate the components: 因此,要获取
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
You can control that findinit('/a/b/c/d/e/f/x.xml')
gives as expected /a/b/c
您可以控制
findinit('/a/b/c/d/e/f/x.xml')
给出预期的/a/b/c
Alternatively if you want to use the pathlib
module, you can search the parts
for a specific component: 或者,如果要使用
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
I found the one-liner finally: 我终于找到了单线:
os.path.join(*list(itertools.takewhile(lambda x: x != 'd', pathlib.PurePath(os.getcwd()).parts)),"d")
wouldnt hve been possible without others answers though. 如果没有其他答案,这是不可能的。 thanks a lot.
非常感谢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.