Koolaidrain

Remove Duplicates

Jan 19th, 2018 (edited)
364
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.00 KB | None | 0 0
  1. find duplicates in directory
  2.  
  3. import sys, os, hashlib, resource
  4.  
  5. if __name__ == '__main__':
  6. if len(sys.argv) < 2: # error, # args
  7. dirName = sys.argv[1]
  8. if not (os.path.exists(dirName) and os.path.isdir(dirName)): # error, not a dir
  9. print(dupes(dirName))
  10.  
  11. def getPaths(dirName):
  12. paths = []
  13. for dirName, subdirList, fileList in os.walk(dirName):
  14. for fileName in fileList:
  15. paths.append(os.path.join(dirName, fileName))
  16. return paths
  17.  
  18. def getChecksum(path):
  19. checksum = hashlib.md5()
  20. pagesize = resource.getpagesize()
  21. with open(path, 'r') as f:
  22. buf = f.read(pagesize)
  23. if not buf: break
  24. checksum.update(buf)
  25. return checksum.digest()
  26.  
  27. # good-enough unique identifier for a path
  28. def getCompoundKey(path):
  29. return (os.path.getsize(path), getChecksum(path))
  30.  
  31. def dupes(dirName):
  32. paths = getPaths(dirName)
  33. dupes, records = [], {}
  34. for path in paths:
  35. key = getCompoundKey(path)
  36. if key in records: dupes.append(key)
  37. else: records.add(key)
  38. for dup in dupes:
  39. os.remove(dup)
Add Comment
Please, Sign In to add comment