将绝对路径转相对路径,其实os.path.relpath(““)直接搞定。不过自己试着写了一个

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值