如何在Windows网络驱动器上使用os.path.relpath获取相对路径?
解决os.path.relpath跨驱动器报错的问题
报错原因很明确:os.path.relpath默认以当前工作目录(你的场景是C盘)作为起始路径,当目标路径位于另一个驱动器(S盘)时,跨驱动器的路径无法计算相对路径,因此抛出ValueError。
要让relpath正常处理网络驱动器路径,只需显式指定起始路径为目标路径所在的驱动器根目录:
import os target_path = r's:\path\to\file' # 显式指定起始路径为S盘根目录 relative_path = os.path.relpath(target_path, start=r's:\\') print(relative_path) # 输出: path\to\file
如果不想硬编码驱动器盘符,可以用os.path.splitdrive动态提取目标路径的驱动器部分,让代码更通用:
import os target_path = r's:\path\to\file' # 拆分驱动器和路径部分 drive, _ = os.path.splitdrive(target_path) # 基于驱动器根目录计算相对路径 relative_path = os.path.relpath(target_path, start=f'{drive}\\') print(relative_path) # 输出: path\to\file
这种方法比切片path[3:]更健壮——如果遇到类似\\server\share\docs\file.txt的网络共享路径,切片会失效,但上述方法依然能正确提取相对路径。
内容的提问来源于stack exchange,提问作者mrgou
相关产品推荐
相关产品推荐

