在Python的目录之间递归地比较重复命名文件的文件大小

2024-09-26 22:51:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不同的目录,有不同的目录树结构。目录A中有一些文件在目录B中,反之亦然,我想确保这些文件的大小相同,这样我就知道哪个副本是正确的(如果它们不同,越大的就是我想要的那个)。这些文件约为1-2 GB。此外,这些目录混合了多种文件类型,我只想比较具有特定扩展名的目录

如何比较相似文件的文件大小并输出匹配和不匹配文件的列表

谢谢:)

更新:抱歉,我的问题含糊不清,我是新来的堆栈溢出。我在这方面做了更多的工作,终于找到了答案。解决方案如下。对于这个测试,有两个dir test1/和test2/都包含file1.txt和file2.txt。两个目录之间的file1.txt相同,file2.txt不同

d1_contents = set(os.path.basename(x) for x in glob.glob("/Users/raycharles/Desktop/test1/*.txt"))
#print d1_contents

d2_contents = set(os.path.basename(x) for x in glob.glob("/Users/raycharles/Desktop/test2/*.txt"))
#print d2_contents

common = list(d1_contents & d2_contents)

common_files = [ f
               for f in common
               if os.path.isfile(os.path.join('/Users/raycharles/Desktop/test1/', f))]

print 'Common files:', common_files

# Compare the directories
match, mismatch, errors = filecmp.cmpfiles('/Users/raycharles/Desktop/test1/', 
                                           '/Users/raycharles/Desktop/test2/', 
                                           common_files, shallow=True)


match = sorted(match)
mismatch = sorted(mismatch)
errors = sorted(errors)

print 'Match:', match
print ""
print 'Mismatch:', mismatch
print ""
print 'Errors:', errors
print ""

这是输出:

Common files: ['file1.txt', 'file2.txt']
Match: ['file1.txt']

Mismatch: ['file2.txt']

Errors: []

Tags: 文件path目录txtoscontentsfilescommon
1条回答
网友
1楼 · 发布于 2024-09-26 22:51:25

解决方案概述:

使用os.walk()查找每个目录中的所有文件,将文件列表转换为集合,并查找集合交集

对于交叉点中的每个文件,使用os.stat()获取其大小(实际上,每个副本获取两个大小)。比较一下尺寸

相关问题 更多 >

    热门问题