2.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163
  1. #!/usr/local/bin/python3
  2. import os, sys
  3. import hashlib
  4. import argparse
  5. import humanfriendly
  6. parser = argparse.ArgumentParser(description='What the dupe!?')
  7. optional = parser._action_groups.pop()
  8. required = parser.add_argument_group('required arguments')
  9. optional.add_argument('--threshold', type=str,
  10. help='Only output files greater than \'size\', e.g. 100M')
  11. optional.add_argument('--exclude', type=str, nargs='?', action='append',
  12. help='Only output files greater than \'size\', e.g. 100M')
  13. optional.add_argument('--sizes', type=str, nargs='+',
  14. help='Only output files greater than \'size\', e.g. 100M')
  15. required.add_argument('--dir', type=str, nargs='?', required=True, action='append',
  16. help='Directory to scan. Can be issued multiple times.')
  17. parser._action_groups.append(optional)
  18. args = parser.parse_args()
  19. if args.sizes:
  20. sizes = args.sizes
  21. sizes.append('larger than '+sizes[-1])
  22. else:
  23. sizes = ['10M', '50M', '100M', '1G', '5G']
  24. sizes.append('larger than '+sizes[-1])
  25. if args.exclude:
  26. exclude=args.exclude
  27. if args.threshold:
  28. threshold = humanfriendly.parse_size(args.threshold)
  29. else:
  30. threshold = 0
  31. def findDup(parentFolder):
  32. # Dups in format {hash:[names]}
  33. dups = {}
  34. print()
  35. for dirName, subdirs, fileList in os.walk(parentFolder):
  36. if args.exclude and dirName in args.exclude:
  37. continue
  38. else:
  39. print(' Scanning %s...' % dirName)
  40. for filename in fileList:
  41. # Get the path to the file
  42. path = os.path.join(dirName, filename)
  43. # Calculate hash
  44. if os.path.exists(path):
  45. # Calculate hash
  46. file_hash = hashfile(path)
  47. # Add or append the file path
  48. if file_hash in dups:
  49. dups[file_hash].append(path)
  50. else:
  51. dups[file_hash] = [path]
  52. return dups
  53. # Joins two dictionaries
  54. def joinDicts(dict1, dict2):
  55. for key in dict2.keys():
  56. if key in dict1:
  57. dict1[key] = dict2[key]
  58. else:
  59. dict1[key] = dict2[key]
  60. def hashfile(path, blocksize = 65536):
  61. file_size = os.path.getsize(path)
  62. # Only hash files larger than threshold (if set)
  63. if threshold == 0 or (threshold > 0 and file_size > threshold):
  64. try:
  65. afile = open(path, 'rb')
  66. hasher = hashlib.md5()
  67. buf = afile.read(blocksize)
  68. while len(buf) > 0:
  69. hasher.update(buf)
  70. buf = afile.read(blocksize)
  71. afile.close()
  72. return hasher.hexdigest()
  73. except:
  74. pass
  75. def printResults(dict1):
  76. final = {}
  77. for size in sizes:
  78. final[size] = []
  79. del size
  80. if threshold > 0:
  81. final[threshold] = []
  82. results = list(filter(lambda x: len(x) > 1, dict1.values()))
  83. for result in results:
  84. file_size = os.path.getsize(result[0])
  85. if threshold > 0:
  86. if file_size >= threshold:
  87. final[threshold].append(result)
  88. else:
  89. count = 0
  90. while count+1 < len(sizes):
  91. try:
  92. if file_size >= humanfriendly.parse_size(sizes[count]) and file_size < humanfriendly.parse_size(sizes[count+1]):
  93. final[sizes[count+1]].append(result)
  94. except:
  95. final[sizes[-1]].append(result)
  96. count += 1
  97. if file_size < humanfriendly.parse_size(sizes[0]):
  98. final[sizes[0]].append(result)
  99. final[threshold]=[False]
  100. if len(results) > 0 and len(final[threshold]) > 0:
  101. print('___________________')
  102. print('\n\033[1;34m\033[1;34m\u25b6 Duplicates Found\033[0m\n')
  103. print(' The following files are identical. The name could differ, but the content is identical')
  104. print('___________________')
  105. new = ['0']
  106. if threshold > 0:
  107. print("\n\033[1;34m\u25b6 Files bigger than %s\033[0m" % humanfriendly.format_size(threshold, binary=True))
  108. for dupe in final[threshold]:
  109. print('___________________\n')
  110. for file in dupe:
  111. print(' %s' % str(file))
  112. print('___________________')
  113. else:
  114. for size in sizes:
  115. new.append(size)
  116. if len(final[size]) > 0:
  117. if size == 'larger than ' + sizes[-2]:
  118. print("\n\033[1;34m\u25b6 >= %s\033[0m" % (new[-2]))
  119. else:
  120. print("\n\033[1;34m\u25b6 %s to %s\033[0m" % (new[-2],size))
  121. for dupe in final[size]:
  122. print('___________________\n')
  123. for file in dupe:
  124. print(' %s' % str(file))
  125. print('___________________')
  126. else:
  127. print('\n\033[1mNo duplicate files found.\033[0m')
  128. if __name__ == '__main__':
  129. if len(sys.argv) > 1:
  130. dups = {}
  131. folders = args.dir
  132. for i in folders:
  133. # Iterate the folders given
  134. if os.path.exists(i):
  135. # Find the duplicated files and append them to the dups
  136. joinDicts(dups, findDup(i))
  137. else:
  138. print('%s is not a valid path, please verify' % i)
  139. sys.exit()
  140. printResults(dups)
  141. else:
  142. print('Usage: python dupFinder.py folder or python dupFinder.py folder1 folder2 folder3')