Python - Move and overwrite files and folders

后端 未结 6 2008
情话喂你
情话喂你 2021-01-30 06:27

I have a directory, \'Dst Directory\', which has files and folders in it and I have \'src Directory\' which also has files and folders in it. What I want to do is move the conte

6条回答
  •  执念已碎
    2021-01-30 06:54

    Since none of the above worked for me, so I wrote my own recursive function. Call Function copyTree(dir1, dir2) to merge directories. Run on multi-platforms Linux and Windows.

    def forceMergeFlatDir(srcDir, dstDir):
        if not os.path.exists(dstDir):
            os.makedirs(dstDir)
        for item in os.listdir(srcDir):
            srcFile = os.path.join(srcDir, item)
            dstFile = os.path.join(dstDir, item)
            forceCopyFile(srcFile, dstFile)
    
    def forceCopyFile (sfile, dfile):
        if os.path.isfile(sfile):
            shutil.copy2(sfile, dfile)
    
    def isAFlatDir(sDir):
        for item in os.listdir(sDir):
            sItem = os.path.join(sDir, item)
            if os.path.isdir(sItem):
                return False
        return True
    
    
    def copyTree(src, dst):
        for item in os.listdir(src):
            s = os.path.join(src, item)
            d = os.path.join(dst, item)
            if os.path.isfile(s):
                if not os.path.exists(dst):
                    os.makedirs(dst)
                forceCopyFile(s,d)
            if os.path.isdir(s):
                isRecursive = not isAFlatDir(s)
                if isRecursive:
                    copyTree(s, d)
                else:
                    forceMergeFlatDir(s, d)
    

提交回复
热议问题