简体   繁体   English

将相对路径解析为 Python 中的另一个相对路径

[英]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?有没有可以实现这一目标的库?

  • I tried 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的绝对路径
  • I tried urllib.parse.urljoin : urljoin(rel_path1, rel_path2) -> main.xml not what I want我试过urllib.parse.urljoinurljoin(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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM