python软链接、相对路径

本文介绍了如何在Python中使用os.symlink创建软链接,以及注意在计算相对路径时,起点必须是文件夹而非文件。针对不同情况,如不同目录下的文件、同一目录内的文件和文件夹,提供了正确的路径处理方法。
摘要由CSDN通过智能技术生成

保存模型时想用一个软链接指向最新的 checkpoint 文件。python 创建软链接用 os.symlink,算两个路径之间的相对路径用 os.path.relpath。但要注意在算相对路径时,起始的路径应是一个文件夹,而不是文件,否则会多一个 ../ 前缀导致错误。

Example

  • os.path.relpath 算相对路径指定 start 时,对 destination link file(的绝对路径)用一次 os.path.dirname
  • 在 windows 创文件夹的软链接时,要设 target_is_directory=True
  • 删文件夹软链接的方法参考 [1,2]。
import os

# 例 1:源文件、软链接在不同目录
f = os.path.expanduser("~/data/NCR-data.tar")
link_f = os.path.expanduser("~/codes/test-data.tar")
print(os.path.relpath(f, start=link_f)) # ../../data/NCR-data.tar
os.symlink(os.path.relpath(f, start=link_f), link_f) # 错
print(os.path.relpath(f, start=os.path.dirname(link_f))) # ../data/NCR-data.tar
os.symlink(os.path.relpath(f, start=os.path.dirname(link_f)), link_f) # 对

# 例 2:源文件、软链接在同一目录
f = os.path.expanduser("~/codes/test.pth")
link_f = os.path.expanduser("~/codes/latest-model.pth")
print(os.path.relpath(f, start=link_f)) # ../test.pth
os.symlink(os.path.relpath(f, start=link_f), link_f) # 错
print(os.path.relpath(f, start=os.path.dirname(link_f))) # test.pth
os.symlink(os.path.relpath(f, start=os.path.dirname(link_f)), link_f) # 对

# 例 3: 文件夹
d = os.path.expanduser("~/data/cityscapes")
link_d = os.path.expanduser("~/codes/test-dir")
print(os.path.relpath(d, link_d)) # ../../data/cityscapes
os.symlink(os.path.relpath(d, link_d), link_d, target_is_directory=True) # 错
print(os.path.relpath(d, os.path.dirname(link_d))) # ../data/cityscapes
os.symlink(os.path.relpath(d, os.path.dirname(link_d)), link_d, target_is_directory=True) # 对

References

  1. linux创建、删除文件夹的软链接
  2. windows软链接
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值