import os
def absdir_to_reldir(absdir):
# absdir
abs_curdir = os.path.abspath(os.curdir)
a_list = absdir.split("\\")
b_list = abs_curdir.split("\\")
print(a_list)
print(b_list)
len_a_list = len(a_list) # ['D:', 'a1', 'b1', 'c1', 'd1', 'a.txt']
len_b_list = len(b_list) # ['D:', 'a1', 'b1', 'c1', 'd1']
new_a_list = a_list.copy()
new_b_list = b_list.copy()
rel_index = 0
for i in range(min(len_a_list, len_b_list)):
if a_list[i] != b_list[i]:
rel_index = i
break
else:
rel_index = i + 1
new_a_list = new_a_list[rel_index:]
new_b_list = new_b_list[rel_index:]
print(f"new_a_list: {new_a_list}")
print(f"new_b_list: {new_b_list}")
if len(new_b_list) == 0:
up_dir = "./"
else:
up_dir = "../" * len(new_b_list)
down_dir = "/".join(new_a_list)
print(f"up_dir: {up_dir}")
print(f"down_dir: {down_dir}")
reldir = up_dir + down_dir
# print(f"reldir: {reldir}")
return reldir
reldir = absdir_to_reldir(r"D:\_1study\code\Python\web\cxwproject_01\serviceApp\urls.py")
print(f"reldir: {reldir}") # ..\..\..\Python\web\cxwproject_01\serviceApp
将绝对路径转相对路径,其实os.path.relpath(““)直接搞定。不过自己试着写了一个
最新推荐文章于 2023-11-04 14:28:37 发布