问题描述
我写了一个 Python 脚本,它将获取目录中所有文件的 md5sum (linux) 现在我想从该目录中获取添加、删除和修改的文件列表
from commands import getoutput
import os
import hashlib
from os import walk
files = []
for dirpath,dirnames,filenames in walk('/home/omkarp/testmd'):
for file in filenames:
files.append(os.path.join(dirpath,file))
md5_cmd = "md5sum %s"
md5sum = []
for f in files:
md5sum.append(getoutput(md5_cmd % (f)))
#print md5sum
dict_md = {}
for d in md5sum:
var = d.split(" ")
dict_md[var[2]] = var[0]
print dict_md
fp = open("/home/omkarp/md5sum.txt",'w')
#for md5 in md5sum:
#fp.write(md5 + "\n")
fp.write(str(dict_md))
fp.close()
解决方法
你可以这样做:
import ast
fp = open("md5sum.txt",'r')
contents = fp.read()
dictionary = ast.literal_eval(contents) # evaluates file content as a dictionnary
for key,value in dict_md.items():
try:
sum = dictionary[key]
except KeyError: # If the key is not in the dictionnary
print "New file"
if sum!=value: # If the md5sum is different
print "File modified"