从字典中提取内容

2024-04-29 18:44:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我用这个函数在159251-TreeOfFunFiles中的文件上建立SHA1签名

def createFileSignature (filename):
    """CreateFileHash (file): create a signature for the specified file
    Returns a tuple containing three values:
    (the pathname of the file, its last modification time, SHA1 hash)
    """
    f = None
    signature = None
    try:
        filesize = os.path.getsize(filename)
        modTime = int(os.path.getmtime(filename))

        f = open(filename, "rb") # open for reading in binary mode
        hash = hashlib.sha1()
        s = f.read(16384)
        while (s):
            hash.update(s)
            s = f.read(16384)
            hashValue = hash.hexdigest()
            signature = (filename, modTime, hashValue)
    except IOError:
        signature = None
    except OSError:
        signature = None
    finally:
        if f:
            f.close()
            return (signature)

我使用python中的os.path模块遍历每个文件。你知道吗

        signatures = {}
        for (dirpath, dirnames, filenames) in os.walk(directory):
            for f in filenames:
                file_path = dirpath + "\\" + f;
                if os.path.exists(file_path):
                    signatures[file_path] = sha.createFileSignature(file_path) #create a signature from the file

这只是创建一个{}签名字典。你知道吗

        for key in signatures:
            if signatures[key] is not None:
                print signatures[key] #(doesnt really check against anything yet)

这个输出('c:\\treeoffunfiles\\README.md', 1349709960, 'f430dc83251684703072a55eee0b0b6a2417c5e4'),现在我的问题是如何从字典中检索2nd3rd元素?我试过print signatures[key][1]但是运气不好


Tags: 文件thepathkeyinnoneforif