Python之使用shutil拷贝文件/文件夹

模块介绍

shutil是Python自带lib中的一员,支持对文件和文件集合的一系列高阶操作。
在这里插入图片描述

  • shutil.copyfileobj
  • shutil.copyfile
  • shutil.copymode
  • shutil.copystat
  • shutil.copy
  • shutil.copy2
  • shutil.ignore_patterns
  • shutil.copytree
  • shutil.rmtree
  • shutil.move
  • shutil.disk_usage
  • shutil.chown
  • shutil.which
  • shutil.make_archive
  • shutil.get_archive_formats
  • shutil.register_archive_format
  • shutil.unregister_archive_format
  • shutil.unpack_archive
  • shutil.register_unpack_format
  • shutil.unregister_unpack_format
  • shutil.get_unpack_formats
  • shutil.get_terminal_size

模块使用

实现从src拷贝文件或文件夹到target。
注:从src拷贝到target,shutil.copytree需要target不存在,否则会报错。
调用shutil.copytree时底层会先调用os.makedirs(dst),继而引发报错。

def shutil_copy_util(src, target):
    """拷贝判断,避免重复拷贝"""
    if not os.path.exists(target):
        if os.path.isdir(src):
            shutil.copytree(src, target)
        elif os.path.isfile(src):
            os.makedirs(target)
            shutil.copy(src, target)
    else:
        if os.path.isdir(src):
            dirs = glob.glob(src+'/*')
            for dir_i in dirs:
                subdir = os.path.basename(dir_i)
                tar_dir = target+'/'+ subdir
                if not os.path.exists(tar_dir):
                    if os.path.isdir(dir_i):
                        shutil.copytree(dir_i, tar_dir)
                    elif os.path.isfile(dir_i):
                        shutil.copy(dir_i, tar_dir)
        elif os.path.isfile(src):
            shutil.copy(src, target)

在这里插入图片描述

参考资料

[1] shutil — 高阶文件操作
[2] Python shutil模块

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TracelessLe

❀点个赞加个关注再走吧❀

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值