python - 如何创建一个 os.walk() 函数来比较两个目录的文件夹和子文件夹?

标签 python for-loop os.walk file-comparison

这是我的问题:假设我想创建一个文件同步功能,它可以遍历两个相似目录的所有文件夹和子文件夹,并检测这两个目录的所有公共(public)文件夹/子文件夹。我通过将 os.walk 模块与 filecmp 模块结合起来进行了尝试。到目前为止,我的代码如下所示:

import filecmp
import os

src=r"C:\Users\j2the\Documents\Test3"
dst=r"C:\Users\j2the\Documents\Test4"


comparison = filecmp.dircmp(dst, src)

for dirpath,dirnames,filenames in os.walk(src):
    for folders in dirnames:
        if folders in comparison.common_dirs:
            print(folders)
            src_folder=os.path.abspath(os.path.join(dirpath,folders))
            dst_folder=os.path.abspath(os.path.join(dst,folders))
            folder_comparison = filecmp.dircmp(dst_folder, src_folder)

            for dirpath1,dirnames1,filenames1 in os.walk(src_folder):

                for subfolders in dirnames1:
                    if subfolders in folder_comparison.common_dirs:
                        print(subfolders)
                        src_subfolder=os.path.abspath(os.path.join(dirpath1,subfolders))
                        dst_subfodler=os.path.abspath(os.path.join(dst_folder,subfolders))
                        subfolder_comparison=filecmp.dircmp(dst_subfodler,src_subfolder)

这是一个非常简单的代码。但是,此代码仅适用于具有 max 的目录。 2 个子文件夹。如果我想分析具有更多子文件夹的目录,我必须在代码中添加大量嵌套循环。当然还有另一种方法可以做到这一点,对吗?我正在考虑创建一个 while 循环,不断遍历每个子文件夹并比较它们,直到没有子文件夹为止,但我根本不知道该怎么做。任何帮助/意见将不胜感激!

最佳答案

您不需要filecmp.dircmp。相反,使用要比较的两个目录对 os.walk 进行两次调用,压缩两个生成器的输出,并对两个子目录使用集合交集输出以查找公共(public)子目录。

请注意,递归遍历的关键是对两个生成器返回的子目录进行就地替换,以便仅保留当前两个目录共有的子目录以进行更深入的遍历进一步比较:

import os
for (root1, dirs1, _), (root2, dirs2, _) in zip(os.walk('dir1'), os.walk('dir2')):
    dirs1[:] = dirs2[:] = set(dirs1).intersection(dirs2)
    for common_dir in dirs1:
      print('Common sub-directory of {} and {}: {}'.format(root1, root2, common_dir))

来自 os.walk 的文档:

When topdown is True, the caller can modify the dirnames list in-place (perhaps using del or slice assignment), and walk() will only recurse into the subdirectories whose names remain in dirnames; this can be used to prune the search...

关于python - 如何创建一个 os.walk() 函数来比较两个目录的文件夹和子文件夹?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58174708/

相关文章:

matlab - 如何在没有 for 循环的情况下对两个矩阵的每一列进行快速矩阵乘法?

c++ - 如何使用基于范围的 for 循环修改 map 中的值?

python - os.walk 中返回的 "root"变量中的完整路径名

python - Html 中出现的文本不存在于 DOM 中

Python/Matplotlib - 双线性插值等高线图

python - 为条件频率分布创建标记和文本的元组

python - 调用函数并打印函数名称

python - 为什么我会收到此关键错误 :0 when using random. choice()?

python - 递归深度有限的旅行目录树

python - 将不同扩展名的文件名写入不同的文本文件