微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用python脚本获取目录中添加的删除和修改的文件列表

如何解决使用python脚本获取目录中添加的删除和修改的文件列表

我写了一个 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"

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。