[英]resolve a relative path to another relative path in Python
I have a relative path which is relative to another relative path, and I want to join them:我有一个相对于另一个相对路径的相对路径,我想加入它们:
rel_path1 = '../../data/a'
rel_path2 = '../../main.xml'
# pseudo function: join_rel_paths
result = join_rel_paths(rel_path1, rel_path2)
# My expectation
expected_result = '../../../main.xml'
assert result == expected_result
Is there any lib which could achieve this?有没有可以实现这一目标的库?
pathlib.Path
: (Path(rel_path1) / Path(rel_path2)).resolve()
-> it returns an absolute path with cwd
pathlib.Path
: (Path(rel_path1) / Path(rel_path2)).resolve()
-> 它返回带有cwd
的绝对路径urllib.parse.urljoin
: urljoin(rel_path1, rel_path2)
-> main.xml
not what I wanturllib.parse.urljoin
: urljoin(rel_path1, rel_path2)
-> main.xml
不是我想要的The expected result of your example should be ../../main.xml
, ie the same as rel_path2
.您的示例的预期结果应该是
../../main.xml
,即与rel_path2
相同。 The two ..
in rel_path2
strip off the last two components from rel_path1
, leaving it as ../..
. rel_path2 中的两个
..
从rel_path2
中剥离最后两个组件,将其rel_path1
为../..
。 Then main.xml
follows.然后
main.xml
。 (But look further down to see how to strip off the last component of rel_path1
.) (但是再往下看,看看如何
rel_path1
的最后一个组件。)
You can achieve this by using os.path.join
followed by os.path.normpath
:您可以通过使用
os.path.join
后跟os.path.normpath
来实现此目的:
rel_path1 = '../../data/a'
rel_path2 = '../../main.xml'
tmp = os.path.join(rel_path1, rel_path2)
result = os.path.normpath(tmp)
This gives '../../data/a/../../main.xml'
for tmp
and '../../main.xml'
for result
.这给出了
'../../data/a/../../main.xml'
为tmp
和'../../main.xml'
为result
。
If you want to treat the last component of rel_path1
as a file (and ignore it), you can use os.path.dirname
to do so:如果您想将
rel_path1
的最后一个组件视为一个文件(并忽略它),您可以使用os.path.dirname
来执行此操作:
rel_path1b = os.path.dirname(rel_path1)
This sets rel_path1b
to '../../data'
, which you can then use in place of rel_path1
to obtain '../../../main.xml'
.这
rel_path1b
设置为'../../data'
,然后您可以使用它代替rel_path1
来获取'../../../main.xml'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.