python - 仅比较文件/文件夹名称的目录,打印任何差异?

标签 python comparison directory-structure python-3.3

我如何递归地比较两个目录(比较应该只基于文件名)并只打印出一个或另一个目录中的文件/文件夹?

我正在使用 Python 3.3。

我看过 filecmp 模块,但是,它似乎并不能完全满足我的需要。最重要的是,它不仅根据文件名来比较文件。

这是我到目前为止所得到的:

import filecmp
dcmp = filecmp.dircmp('./dir1', './dir2')
dcmp.report_full_closure()

dir1 看起来像这样:

dir1
  - atextfile.txt
  - anotherfile.xml
  - afolder
    - testscript.py
  - anotherfolder
    - file.txt
  - athirdfolder

dir2 看起来像这样:

dir2
  - atextfile.txt
  - afolder
    - testscript.py
  - anotherfolder
    - file.txt
    - file2.txt

我希望结果看起来像这样:

files/folders only in dir1
  * anotherfile.xml
  * athirdfolder

files/folders only in dir2
  * anotherfolder/file2.txt

我需要一种简单的 pythonic 方法来仅基于文件/文件夹名称比较两个目录,并打印出差异。

此外,我需要一种方法来检查目录是否相同。

注意:我在 stackoverflow 和 google 上搜索过类似的内容。我看到很多关于如何在考虑文件内容的情况下比较文件的示例,但我找不到任何关于文件名的信息。

最佳答案

我的解决方案使用 set() 类型来存储相对路径。那么比较只是一个集合减法的问题。

import os
import re

def build_files_set(rootdir):
    root_to_subtract = re.compile(r'^.*?' + rootdir + r'[\\/]{0,1}')

    files_set = set()
    for (dirpath, dirnames, filenames) in os.walk(rootdir):
        for filename in filenames + dirnames:
            full_path = os.path.join(dirpath, filename)
            relative_path = root_to_subtract.sub('', full_path, count=1)
            files_set.add(relative_path)

    return files_set

def compare_directories(dir1, dir2):
    files_set1 = build_files_set(dir1)
    files_set2 = build_files_set(dir2)
    return (files_set1 - files_set2, files_set2 - files_set1)

if __name__ == '__main__':
    dir1 = 'old'
    dir2 = 'new'
    in_dir1, in_dir2 = compare_directories(dir1, dir2)

    print '\nFiles only in {}:'.format(dir1)
    for relative_path in in_dir1:
        print '* {0}'.format(relative_path)

    print '\nFiles only in {}:'.format(dir2)
    for relative_path in in_dir2:
        print '* {0}'.format(relative_path)

讨论

  • 主力是函数 build_files_set()。它遍历一个目录并创建一组相对文件/目录名称

  • 函数 compare_directories() 获取两组文件并返回差异——非常直接。

关于python - 仅比较文件/文件夹名称的目录,打印任何差异?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15069091/

相关文章:

python - Django all-auth 删除在注册表单中两次询问密码

performance - 矩阵中行的成对比较

linux - 我怎样才能将linux centos中的树形目录转换为文本文件

python - 如何使用 Queryset 的值填充嵌套字典作为 Django 中的列表

python - 在深度优先搜索有向图的同时跟踪时间

python - key 错误 : nan in dict

performance - 使用 XOR 而不是减法的 x86 比较指令

c# - 测试按位枚举值

java - 为什么 Java 源文件进入目录结构?

Java EE i18n 和默认项目结构