【问题标题】:Compare files in two directories with python to look for files that are in one directory but not the other -agnostic to subdirectory structure使用 python 比较两个目录中的文件以查找一个目录中但不在另一个目录中的文件 - 与子目录结构无关
【发布时间】:2020-02-20 03:31:54
【问题描述】:

尝试将我们当前的项目媒体服务器 (dir1) 与备份 (dir2) 进行比较,以查看删除了哪些文档。两者都是windows目录。 许多文件已被改组到新的子目录中,但并没有丢失。因为使用递归和 filecmp.dircmp 更改了目录结构,所以这篇文章将不起作用: Recursively compare two directories to ensure they have the same files and subdirectories

另外一个考虑是不同的文件会有相同的文件名,所以比较需要比较文件大小、修改日期等来判断两个文件是否相同。

我想要什么 sudo 代码:

def find_missing_files(currentDir, backup):
    <does stuff>
    return <List of Files in backup that are not in currentDir>

我有什么:

def build_file_list(someDir, fileList = []):
    for root, dirs, files in os.walk(someDir):
        if files:
            for file in files:
                filePath = os.path.join(root, file)
                if filePath not in fileList:
                    fileList.append(filePath)
    return fileList

def cmp_file_lists(dir1, dir2):
    dir1List = build_file_list(dir1)
    dir2List = build_file_list(dir2)

    for dir2file in dir2List:
        for dir1file in dir1List:
            if filecmp.cmp(dir1file, dir2file):
                dir1List.remove(dir1file)
                dir2List.remove(dir2file)
                break
    return (dir1List, dir2List)

编辑:在上面的代码中,我遇到了一个问题,即 dir2List.remove(dir2file) 抛出 dir2file 不在 dir2List 中的错误,因为(它看起来)不知何故 dir2list 和 dir1List 都是同一个对象。不知道这是怎么回事。

我不知道这是否可以通过 filecmp.dircmp 更轻松地完成,但我错过了它?或者如果这是实现我正在寻找的最佳方法? ...或者我应该从 dir2 和我们的 os.walk 中获取每个文件以在 dir1 中查找它?

【问题讨论】:

    标签: python python-3.x windows directory


    【解决方案1】:

    我可以建议一个替代方案吗?使用pathlibrglob 方法,一切都会变得容易得多(如果你真的不知道子目录的话):

    from pathlib import Path
    
    def cmp_file_lists(dir1, dir2):
        dir1_filenames = set(f.name for f in Path(dir1).rglob('*'))
        dir2_filenames = set(f.name for f in Path(dir2).rglob('*'))
        files_in_dir1_but_not_dir2 = dir1_filenames - dir2_filenames 
        files_in_dir2_but_not_dir1 = dir2_filenames - dir1_filenames 
        return dir1_filenames, dir2_filenames
    

    【讨论】:

    • 用这个做实验......但它不只是比较文件名吗?我将拥有具有相同文件名的不同文件(显然在不同的目录中)因此使用 filecmp.cmp 寻找其他统计数据进行比较的原因......我认为。它还应该返回 files_in_dir2_but_not_dir1 和 files_in_dir1_but_not_dir2,不是吗?
    • @constdocconstdoc 它只会比较名称,这是真的,但您没有指定 filecmp.cmp 的作用。您始终可以将此级别的比较添加到此代码中,或者将文件与集合中的 name 进行比较。这里的基本思想是向您展示在目录中搜索的替代方法,您如何使用它取决于您
    • 感谢您强调了一种构建文件列表的方法,但比较文件是这里的问题。尽管如此,如果我最终使用文件列表,这可能有助于构建列表。
    猜你喜欢
    • 1970-01-01
    • 2013-05-23
    • 1970-01-01
    • 2014-12-19
    • 2015-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-02
    相关资源
    最近更新 更多