声明:本站文章均为作者个人原创,图片均为实际截图。如有需要请收藏网站,禁止转载,谢谢配合!!!

说明:调用方式为 python + 脚本文件名.py + 源路径 + 目标路径

1.仅复制一个文件夹

py -3 copy_dir.py test E:\badianboke1 E:\badianboke2

将test文件夹从 E:\badianboke1 复制到 E:\badianboke2

copy_single_dir.py 文件内容如下

import os
import sys
import stat
import shutil

class Copy_Single_Dir():
    def __init__(self, dirName, fromPath,  toPath):
        self.dirName = dirName
        self.fromPath = fromPath
        self.toPath = toPath

    def doCopy(self):
        fromDir = os.path.join(self.fromPath, self.dirName)
        toDir = os.path.join(self.toPath, self.dirName)
        if not os.path.isdir(fromDir):
            print('Source Dir is wrong!--badianboke')
            return
        if os.path.isfile(toDir):
            print('Target is file but not dir, wrong target!--badianboke')
            return
        if os.path.exists(toDir):
            shutil.rmtree(toDir, onerror = self.handleRemoveError)

        shutil.copytree(fromDir, toDir)

        print('copy single dir successfully')

    def handleRemoveError(self, func, path, exe_info):
        # 先授权,再删除
        os.chmod(path, stat.S_IWRITE)
        if os.path.isfile(path):
            os.remove(path)
        if os.path.isdir(path):
            shutil.rmtree(path)


if __name__ == '__main__':
    task = Copy_Single_Dir(sys.argv[1], sys.argv[2], sys.argv[3])
    task.doCopy()

2.复制多个文件夹

py -3 copy_dir.py list.txt E:\badianboke1 E:\badianboke2

将list.txt内所列的所有文件夹从 E:\badianboke1 复制到 E:\badianboke2

dir1
dir2
dir3

copy_single_dir.py 文件内容如下

import os
import sys
import stat
import shutil

class Copy_Multi_Dir():
    def __init__(self, dirName, fromPath,  toPath):
        self.dirName = dirName
        self.fromPath = fromPath
        self.toPath = toPath

    def doCopy(self):
        fromDir = os.path.join(self.fromPath, self.dirName)
        toDir = os.path.join(self.toPath, self.dirName)
        if not os.path.isdir(fromDir):
            print('Source Dir is wrong!--badianboke')
            return
        if os.path.isfile(toDir):
            print('Target is file but not dir, wrong target!--badianboke')
            return
        if os.path.exists(toDir):
            shutil.rmtree(toDir, onerror = self.handleRemoveError)

        shutil.copytree(fromDir, toDir)

        print('copy single dir successfully')

    def handleRemoveError(self, func, path, exe_info):
        # 先授权,再删除
        os.chmod(path, stat.S_IWRITE)
        if os.path.isfile(path):
            os.remove(path)
        if os.path.isdir(path):
            shutil.rmtree(path)


if __name__ == '__main__':
    task = Copy_Single_Dir(sys.argv[1], sys.argv[2], sys.argv[3])
    task.doCopy()



点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论