我们可能会遇到这样一种情况,有两个文件夹,里面大部分的文件相同,少部分不一致,我们需要找出两个目录下差异的文件。
主要用到的函数为 os.wall() 和 shutil.copy() ,前者用来遍历文件夹,后者用来拷贝文件。
1. 遍历目录
os.walk() 函数的用法前一篇中讲过,这里用它将 path 路径下的所有文件遍历找到。
fileList = []
for root, dirs, files in os.walk(path):
    for fileName in files:
        file = os.path.join(root, name)
        fileList.push(file)
print(fileList)2. 比较两个目录差异
实现的思路是,先遍历 path1 获取该路径下所有文件,然后遍历 path2 时,判断 path2 的文件是否在 path1 的文件列表中。
def compareDirs(path1, path2):
    fileList = []
    for root, dirs, files in os.walk(path1):
        for fileName in files:
            file = os.path.join(root, name)
            # 去除 path1 路径,仅保留文件相对路径
            file = file.replace(path1, "")
            fileList.push(file)
    
    diffList = []
    for root, dirs, files in os.walk(path2):
        for fileName in files:
            file = os.path.join(root, name)
            file = file.replace(path1, "")
            if file not in fileList:
                diffList.push(file)
    return diffList若 path2 中的文件不在 path1 中,则将该文件放入 diffList 中返回。
3. 拷贝差异文件
如果需要将差异的文件拷贝到新的文件夹中,则可以参考以下的代码。
import shutil
def copyFiles(srcDir, destDir, fileList):
    for file in fileList:
        # 需要提取出不包含文件名的文件路径
        destPath = destDir + "/".join(file.split("\\")[0:-1]) + "/"
        if not os.path.exists(destPath):
            os.makedirs(destPath)
        shutil.copy(srcDir + file, destPath)4. 完整代码
完整参考代码如下:
import os, shutil
def compareDirs(path1, path2):
    fileList = []
    for root, dirs, files in os.walk(path1):
        for fileName in files:
            file = os.path.join(root, name)
            # 去除 path1 路径,仅保留文件相对路径
            file = file.replace(path1, "")
            fileList.push(file)
    
    diffList = []
    for root, dirs, files in os.walk(path2):
        for fileName in files:
            file = os.path.join(root, name)
            file = file.replace(path1, "")
            if file not in fileList:
                diffList.push(file)
    return diffList
def copyFiles(srcDir, destDir, fileList):
    for file in fileList:
        # 需要提取出不包含文件名的文件路径
        destPath = destDir + "/".join(file.split("\\")[0:-1]) + "/"
        if not os.path.exists(destPath):
            os.makedirs(destPath)
        shutil.copy(srcDir + file, destPath)
        
if __name__ == "__main__":
    path1 = "D://data1"
    path2 = "D://data2"
    destPath = "D://data3"
    diff = compareDirs(path1, path2)
    copyFiles(path2, destPath, diff)

此处评论已关闭