zoukankan      html  css  js  c++  java
  • python 小程序 复制目录树

    1. 将一个目录树完全复制到另外一个目录下面

    import os, sys
    
    """
    复制目录树
    """
    
    maxloadsize = 1024 * 1024
    
    
    def copyfile(frompath, topath, maxloadsize= maxloadsize):
        """
        单个文件的复制
        :param frompath:原文件
        :param topath: 复制到的文件
        :param maxloadsize: 复制最大块
        :return:
        """
        fromfilename = os.path.split(frompath)[1]
        (dirpath,filename) = os.path.split(topath)
        if fromfilename != filename:
            topath = os.path.join(dirpath, fromfilename)
            print("changed copy file name:" + topath)
        if os.path.getsize(frompath) <= maxloadsize:
            with open(frompath, "rb") as fromfile:
                with open(topath, "wb") as tofile:
                    bytes = fromfile.read(maxloadsize)
                    tofile.write(bytes)
        else:
            with open(frompath, "rb") as fromfile:
                with open(topath, "wb") as tofile:
                    while True:
                        bytes = fromfile.read(maxloadsize)
                        if not bytes:break
                        tofile.write(bytes)
    
    
    def copytree(dirfrom, dirto, verbose = 0):
        if not os.path.isdir(dirto):
            os.mkdir(dirto)
        fount = tcount =0
        for filename in os.listdir(dirfrom):
            pathfrom = os.path.join(dirfrom, filename)
            pathto = os.path.join(dirto, filename)
            if not os.path.isfile(pathfrom):
                # 目录循环copy
                try:
                    os.mkdir(pathfrom)
                    fc,tc = copytree(pathfrom, pathto)
                    fount += fc
                    tcount += tc
                except:
                    print("Error copying from {0} to {1}".format(pathfrom, pathto))
            else:
                # 文件直接copy
                try:
                    print("copy from {0} to {1}".format(pathfrom, pathto))
                    copyfile(pathfrom, pathto)
                    fount += 1
                except:
                    print("Error copying from {0} to {1}".format(pathfrom, pathto))
        return (fount, tcount)
    
    if __name__ == '__main__':
        #copyfile("../testdir1/test1.pdf", "../testdir/testfdf.pdf")
        copytree("../lession6","../less")
    

      

  • 相关阅读:
    给你的QQ秀添加声音方法,如何打开QQ聊天窗口播放声音
    Flash 重绘的发生
    nexus one使用apndroid关不掉联通3G的解决办法 [转]
    \\无题
    \\入手N1
    WinRAR的三种安全战术
    如何巧用DOS命令快速把系统问题看个透
    Adobe Creative Suite 5 Master Collection 尝鲜
    \\无题
    质量管理工具Sonar中名词解释
  • 原文地址:https://www.cnblogs.com/someoneHan/p/6254335.html
Copyright © 2011-2022 走看看