2017-01-01 38 views
-3

我有两个不同的目录,具有不同的目录树结构。目录A有一些在目录B中的文件,反之亦然,我想确保这些文件的大小相同,以便我知道哪个副本是正确的(如果它们不同,则需要更大的副本)。这些文件是〜1-2 GB。另外,这些目录有多种文件类型,我只想比较具有特定扩展名的文件。在Python中的目录之间递归地比较重复命名文件的文件大小

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

谢谢:)

更新:很抱歉的含糊不清的问题,我是新来的堆栈溢出。我更多地研究了这一点,并能够弄清楚。解决方案如下。对于此测试,有两个目录test1 /和test2 /都包含file1.txt和file2.txt。 file1.txt在两个dirs之间是相同的,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: [] 
+1

它看起来像你希望我们为你写一些代码。尽管许多用户愿意为遇险的编码人员编写代码,但他们通常只在海报已尝试自行解决问题时才提供帮助。展示这一努力的一个好方法是包含迄今为止编写的代码,示例输入(如果有),预期输出以及实际获得的输出(控制台输出,回溯等)。您提供的细节越多,您可能会收到的答案就越多。检查[FAQ](http://stackoverflow.com/tour)和[如何提问](http://stackoverflow.com/help/how-to-ask)。 –

回答

1

解决方案的概要:

使用os.walk()找到每个目录下的所有文件,该文件列出转换成集,并找到设置交叉点。

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

相关问题