在python中是否有办法将两个路径与os.path
或任何其他不重复常见子文件夹的库组合在一起?即。
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
答案 0 :(得分:2)
我认为你必须手动完成,我不认为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
答案 1 :(得分:0)
您可以使用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
答案 2 :(得分:0)
你可以尝试:
>>> 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'
或者,如果root和rel_path没有重叠'部分:
>>> 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'