Guest User

Untitled

a guest
Dec 17th, 2017
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | None | 0 0
  1. import hashlib
  2. import os
  3. import csv
  4. from collections import OrderedDict
  5.  
  6. def hashFiles(__location, topDown=False):
  7. """Return List of file Path + filename : md5 hash"""
  8. hashlist = []
  9. list2dict = {}
  10. if os.path.isdir(__location):
  11. for dirs, subdir, filename in os.walk(__location, topdown=False):
  12. for file in filename:
  13. fhash = hashlib.md5()
  14. fhash.update(open(dirs + '/' + file).read())
  15. calc_hash = fhash.hexdigest()
  16. hashlist.append(dirs + '/' + file + ':' + calc_hash)
  17. list2dict = dict([x.split(':')[0], x.split(':')[1]] for x in hashlist)
  18. return list2dict
  19.  
  20. if os.path.isfile(__location):
  21. fhash = hashlib.md5()
  22. fhash.update(open(__location).read())
  23. calc_hash = fhash.hexdigest()
  24. hashlist.append(__location + ':' + calc_hash)
  25. list2dict = dict([x.split(':')[0], x.split(':')[1]] for x in hashlist)
  26. return list2dict
  27.  
  28. def saveToCSV(hashlists, csvfilename):
  29. """Write hashFile list in to csv file"""
  30.  
  31. ordered_fields = OrderedDict([('Path', None), ('Hash', None)])
  32. write = csv.DictWriter(open(csvfilename, "a+"), fieldnames=ordered_fields)
  33. write.writeheader()
  34. for k,v in hashlists.iteritems():
  35. data = dict({"Path": k, "Hash": v})
  36. write = csv.DictWriter(open(csvfilename, "a+"), fieldnames=ordered_fields)
  37. write.writerow(data)
  38. return True
  39.  
  40. def getValueFromCSV(csvfilename):
  41. """Convert CSV File in to List.
  42. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  43. - Required header Name Path and Hash
  44. """
  45. reader = csv.DictReader(open(csvfilename))
  46. new_list = []
  47. for k in reader:
  48. csv_fpath = k['Path']
  49. csv_hash = k['Hash']
  50. convert = csv_fpath + ':' + csv_hash
  51. new_list.append(convert)
  52. return new_list
  53.  
  54.  
  55. # access to function
  56. def main():
  57. location = "/tmp/test"
  58. csv_file = "/tmp/test/new.csv"
  59. hashdict = hashFiles(location, topDown=True)
  60. saveToCSV(hashdict, csv_file)
  61. getValueFromCSV(csv_file)
  62.  
  63. # run prog
  64. if __name__ == "__main__":
  65. main()
Add Comment
Please, Sign In to add comment