Python发现文件路径之间的差异 [英] Python find difference between file paths

查看:73
本文介绍了Python发现文件路径之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆文件路径,例如:

I have a bunch of file paths, such as:

path1 = "./base/folder1/subfolder"
path2 = "./base/folder2/"

我正在尝试编写一个函数,该函数可以为我提供路径之间的相对差异.使用上面的路径:

I am trying to write a function that can give me the relative difference between the paths. Using the paths above:

>>> get_path_difference(path1, path2)
"../../folder2"
>>> get_path_difference(path2, path1)
"../folder1/subfolder"

我已经浏览过 os.path 模块,因为这似乎很常见,但是我不知道该术语还是不存在.

I've had a look through the os.path module, since it seems like this should be a common thing, but either I don't know the terminology or it isn't there.

推荐答案

您可以使用

You can use os.path.relpath:

>>> path1 = "./base/folder1/subfolder"
>>> path2 = "./base/folder2/"
>>> import os
>>> os.path.relpath(path1, path2)
'../folder1/subfolder'
>>> os.path.relpath(path2, path1)
'../../folder2'

这篇关于Python发现文件路径之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆