See see if two files have the same content in python
For comparing, you can use the filecmp module (http://docs.python.org/library/filecmp.html):
>>> import filecmp
>>> filecmp.cmp('F1.txt, 'F2.txt')
True
>>> filecmp.cmp('F1.txt', 'F3.txt')
False
So one way to tackle it would be (not at all elegant but it does work):
import filecmp
files = ['F1.txt', 'F2.txt', 'F3.txt', 'F4.txt', 'F5.txt']
comparisons = {}
for itm in range(len(files)):
try:
res = filecmp.cmp(files[itm], files[itm+1])
comparisons[str(files[itm]) + ' vs ' + str(files[itm+1])] = res
except:
pass
try:
res = filecmp.cmp(files[itm], files[itm+2])
comparisons[str(files[itm]) + ' vs ' + str(files[itm+2])] = res
except:
pass
try:
res = filecmp.cmp(files[itm], files[itm+3])
comparisons[str(files[itm]) + ' vs ' + str(files[itm+3])] = res
except:
pass
try:
res = filecmp.cmp(files[itm], files[itm+4])
comparisons[str(files[itm]) + ' vs ' + str(files[itm+4])] = res
except:
pass
print(comparisons)
Gives:
{'F1.txt vs F2.txt': True, 'F1.txt vs F5.txt': False, 'F2.txt vs F4.txt': True,
'F3.txt vs F4.txt': False, 'F1.txt vs F4.txt': True, 'F2.txt vs F3.txt': False,
'F2.txt vs F5.txt': False, 'F1.txt vs F3.txt': False, 'F3.txt vs F5.txt': False,
'F4.txt vs F5.txt': False}
As for the other part of your question, you can use the built-in shutil
and os
modules like so:
import shutil
import os
if filecmp.cmp('F1.txt', 'F2.txt') is True:
shutil.move(os.path.abspath('F1.txt'), 'C:\\example\\path')
shutil.move(os.path.abspath('F2.txt'), 'C:\\example\\path')
UPDATE: better answer, modified from @zalew's answer : https://stackoverflow.com/a/748879/5247482
import shutil
import os
import hashlib
def remove_duplicates(dir):
unique = []
for filename in os.listdir(dir):
if os.path.isfile(dir+'\\'+filename):
print('--Checking ' + dir+'\\'+filename)
filehash = hashlib.md5(filename.encode('utf8')).hexdigest()
print(filename, ' has hash: ', filehash)
if filehash not in unique:
unique.append(filehash)
else:
shutil.move(os.path.abspath(filename), 'C:\\example\\path\\destinationfolder')
return
remove_duplicates('C:\\example\\path\\sourcefolder')