Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将两个路径与公共文件夹合并_Python - Fatal编程技术网

Python 将两个路径与公共文件夹合并

Python 将两个路径与公共文件夹合并,python,Python,python中有没有办法将两个路径与os.path或任何其他不重复公共子文件夹的库组合在一起?i、 e 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.join: import os root = '/

python中有没有办法将两个路径与
os.path
或任何其他不重复公共子文件夹的库组合在一起?i、 e

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.join

import os

root = '/home/user/test'

rel_path = 'test/files/file.txt'

head, tail = os.path.split(root)
final = os.path.join(head, rel_path)

print(final)
#  /home/user/test/files/file.txt 
你可以试试:

>>> import os
>>> root = '/home/user/test'
>>> rel_path = 'test/files/file.txt'
>>> os.path.join(root, '../', rel_path)
'/home/user/test/../test/files/file.txt'
或者,如果根路径和rel_路径没有“重叠”部分:

>>> os.path.join(root, '../' if root.split('/')[-1] == rel_path.split('/')[0] else '' , rel_path)
'/home/user/test/../test/files/file.txt'
>>> root =  '/home/user/test/files'
>>> os.path.join(root, '../' if root.split('/')[-1] == rel_path.split('/')[0] else '' , rel_path)
'/home/user/test/files/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

我对此表示怀疑,因为在
test
文件夹中可能有一个
test
文件夹..是的,我想知道是否有任何内置或库可以使用,如果
root='/home/user/test/files'
?你必须去递归如果
root='/home/user/test/files'
?您必须进行递归。不幸的是,只有当根的最后一部分与rel路径的第一部分匹配时,这才起作用。要递归地执行此操作,必须编写自定义代码。递归会带来它自己的一系列问题。我知道,这就是我为什么要“问”的原因。OP并没有将重叠的大小限制在一个公共文件夹中。@Ev.Kounis,根据您的反馈,查看我的答案:)