gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 07:11:49 24 4
gpt4 key购买 nike

这是我的问题:假设我想创建一个文件同步功能,它可以遍历两个相似目录的所有文件夹和子文件夹,并检测这两个目录的所有公共(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com