首页 > 代码库 > python 小程序 复制目录树

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")

  

python 小程序 复制目录树