python编写的linux下使用的xcopy代码

2022-03-11 00:00:00 python 代码 编写

这个python函数模仿windows下的xcopy命令编写,可以用在linux下

"""
作者:皮蛋编程(https://www.pidancode.com)
创建日期:2022/3/23
功能描述:python编写的linux下使用的xcopy代码
"""

import os, shutil, fnmatch


class XCopy:
    def __init__(self, src, dst, filters=['*']):
        self.filters = filters
        self.copytree(src, dst)

    def copytree(self, src, dst):
        """
        Based in shutil.copytree()
        """
        names = os.listdir(src)
        if not os.path.isdir(dst):
            os.makedirs(dst)
        errors = []
        for name in names:
            srcname = os.path.join(src, name)
            dstname = os.path.join(dst, name)
            if os.path.isdir(srcname):
                self.copytree(srcname, dstname)
            elif os.path.isfile(srcname):
                if self.filterName(name):
                    print("copy:", name, dstname)
                    shutil.copy2(srcname, dstname)
        shutil.copystat(src, dst)

    def filterName(self, fileName):
        for filter in self.filters:
            if fnmatch.fnmatch(fileName, filter):
                return True
        return


xcopy = XCopy(src='./', dst='../temp')

以上代码在python3.9+mac环境下测试通过。

相关文章