Skip to main content
 首页 » 编程设计

python之将两个路径与公共(public)文件夹组合

2024年10月01日8落叶无声

在 python 中有没有一种方法可以将两条路径与 os.path 或任何其他不重复公共(public)子文件夹的库结合起来?即

root = '/home/user/test' 
 
rel_path = 'test/files/file.txt' 
 
os.combine(root, rel_path) 

并返回 /home/user/test/files/file.txt 而不是 /home/user/test/test/files/file.txt

请您参考如下方法:

我认为你必须手动完成,我不认为 os.path 实现了这个功能。

也许可以尝试这样的事情:

def combine_with_duplicate(root, rel_path): 
    rs = root.split("/") 
    rps = rel_path.split("/") 
    popped = False 
    for v in rs: 
        if v == rps[0]: 
            rps.pop(0) 
            popped = True 
        elif popped: 
            break 
 
    return "/".join(rs+rps) 
 
 
print(combine_with_duplicate('/home/user/test', 'test/files/file.txt')) 
# /home/user/test/files/file.txt 
print(combine_with_duplicate('/home/user', 'test/files/file.txt')) 
# /home/user/test/files/file.txt 
print(combine_with_duplicate('/home/user/test', 'user/test/files/file.txt')) 
# /home/user/test/files/file.txt