Pythonはキューの広さを利用してファイルを遍歴、コピーする


"""

"""
import os
import collections

"""
@para1   sourcePath     
@para1   targetPath      
"""


def getDirAndCopyFile(sourcePath,targetPath):

    if not os.path.exists(sourcePath):
        return

    if not os.path.exists(targetPath):
        os.makedirs(targetPath)
    tempTar = targetPath
    #           
    queuePath = collections.deque()
    #              
    queueTarPath = collections.deque()
    #       
    queuePath.append(sourcePath)
    #           
    queueTarPath.append(targetPath)

    while True:

        #        if len(queuePath)==0:
            break


        #               
        path = queuePath.popleft()
        #              
        tarpath=queueTarPath.popleft()

        #   path
        for fileName in os.listdir(path):
            #    
            absPath = os.path.join(path,fileName)
            absTar = os.path.join(tarpath,fileName)

            #             if os.path.isfile(absPath):
                rbf = open(absPath, 'rb')
                wbf = open(absTar, 'wb')
                while True:
                    content = rbf.readline(1024 * 1024 * 5)
                    if len(content) == 0:
                        break
                    wbf.write(content)
                    wbf.flush()
                rbf.close()
                wbf.close()

            #            if os.path.isdir(absPath):
                if os.path.exists(absTar):
                    os.rmdir(absTar)
                os.mkdir(absTar)
                queueTarPath.append(absTar)
                queuePath.append(absPath)


if __name__ == '__main__':

    sourcePath = r"     "
    targetPath = r"      "
    getDirAndCopyFile(sourcePath,targetPath)