python里怎么复制链接_在Python中复制符号链接

Python3follow_symlinks

在Python 3中,shutil的大多数复制方法都学习了follow_symlinks参数,如果选择了该参数,它将保留符号链接。

例如,对于shutil.copy:shutil.copy(src, dest, follow_symlinks=False)shutil.copy(src, dst, *, follow_symlinks=True)

Copies the file src to the file or directory dst. src and dst should be strings. If dst specifies a directory, the file will be copied into dst using the base filename from src. Returns the path to the newly created file.

If follow_symlinks is false, and src is a symbolic link, dst will be created as a symbolic link. If follow_symlinks` is true and src is a symbolic link, dst will be a copy of the file src refers to.

但是,这有一个问题:如果试图覆盖现有文件或符号链接,它将失败:FileExistsError: [Errno 17] File exists: 'b' -> 'c'

与成功覆盖的follow_symlinks=True不同。

同样的情况也发生在os.symlink上,因此我最终使用了:#!/usr/bin/env python3

import shutil

import os

def copy(src, dst):

if os.path.islink(src):

if os.path.lexists(dst):

os.unlink(dst)

linkto = os.readlink(src)

os.symlink(linkto, dst)

else:

shutil.copy(src, dst)

if __name__ == '__main__':

os.symlink('c', 'b')

os.symlink('b', 'a')

copy('a', 'b')

with open('c', 'w') as f:

f.write('a')

with open('d', 'w'):

pass

copy('c', 'd')

copy('a', 'c')

在Ubuntu 18.10,Python 3.6.7中测试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值