码迷,mamicode.com
首页 > 编程语言 > 详细

python 小程序 复制目录树

时间:2017-01-05 23:51:12      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:mkdir   return   list   完全   from   not   param   err   文件   

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 小程序 复制目录树

标签:mkdir   return   list   完全   from   not   param   err   文件   

原文地址:http://www.cnblogs.com/someoneHan/p/6254335.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!