Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import hashlib
- import os
- import csv
- from collections import OrderedDict
- def hashFiles(__location, topDown=False):
- """Return List of file Path + filename : md5 hash"""
- hashlist = []
- list2dict = {}
- if os.path.isdir(__location):
- for dirs, subdir, filename in os.walk(__location, topdown=False):
- for file in filename:
- fhash = hashlib.md5()
- fhash.update(open(dirs + '/' + file).read())
- calc_hash = fhash.hexdigest()
- hashlist.append(dirs + '/' + file + ':' + calc_hash)
- list2dict = dict([x.split(':')[0], x.split(':')[1]] for x in hashlist)
- return list2dict
- if os.path.isfile(__location):
- fhash = hashlib.md5()
- fhash.update(open(__location).read())
- calc_hash = fhash.hexdigest()
- hashlist.append(__location + ':' + calc_hash)
- list2dict = dict([x.split(':')[0], x.split(':')[1]] for x in hashlist)
- return list2dict
- def saveToCSV(hashlists, csvfilename):
- """Write hashFile list in to csv file"""
- ordered_fields = OrderedDict([('Path', None), ('Hash', None)])
- write = csv.DictWriter(open(csvfilename, "a+"), fieldnames=ordered_fields)
- write.writeheader()
- for k,v in hashlists.iteritems():
- data = dict({"Path": k, "Hash": v})
- write = csv.DictWriter(open(csvfilename, "a+"), fieldnames=ordered_fields)
- write.writerow(data)
- return True
- def getValueFromCSV(csvfilename):
- """Convert CSV File in to List.
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- - Required header Name Path and Hash
- """
- reader = csv.DictReader(open(csvfilename))
- new_list = []
- for k in reader:
- csv_fpath = k['Path']
- csv_hash = k['Hash']
- convert = csv_fpath + ':' + csv_hash
- new_list.append(convert)
- return new_list
- # access to function
- def main():
- location = "/tmp/test"
- csv_file = "/tmp/test/new.csv"
- hashdict = hashFiles(location, topDown=True)
- saveToCSV(hashdict, csv_file)
- getValueFromCSV(csv_file)
- # run prog
- if __name__ == "__main__":
- main()
Add Comment
Please, Sign In to add comment