[英]Most pythonic way to relocate a path to a new root directory
I have the following: 我有以下内容:
a = "/my/absolute/path"
b = "my/relative/path"
root = "/new/root/dir"
print relocate_path(a, root)
print relocate_path(b, root)
I would like to get: 我想得到:
/new/root/dir/my/absolute/path
/new/root/dir/my/relative/path
How to effectively implement relocate_path
in a pythonic way? 如何有效地实施
relocate_path
在Python的方式? Is there something like that in the standard library? 标准库中是否有类似的东西? (I have tried in os.path , but found nothing)
(我曾在os.path中尝试过,但一无所获)
You need os.path.join
for relative paths. 您需要
os.path.join
作为相对路径。 In case of absolute path I think the best thing you can do is stripping the leading slash. 在绝对路径的情况下,我认为您可以做的最好的事情是去除斜线。
Something like this: 像这样:
def relocate_path(new_root, path):
return os.path.join(new_root, path.lstrip('/'))
To get a path relative to root given an absolute path you can also do: 要获得相对于root的给定绝对路径,您还可以执行以下操作:
>>> os.path.relpath('/absolute/path', '/')
'absolute/path'
but I don't think it's more crossplatform than just stripping the slash. 但是我不认为它比跨斜杠更具跨平台性。 I've tried playing with
relpath
on Windows a bit and I should say I have no idea how it works. 我试过在Windows上使用
relpath
,我应该说我不知道它是如何工作的。
Just now I wrote a small python script, i don't know whether it can help you. 刚才我写了一个小的python脚本,我不知道它是否可以帮助您。
import re def relocate_path(path,root): pattern = re.compile(r'^/') match = pattern.match(path) if match: return (root+path) else: return (root+"/"+path)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.