0

我正在使用此功能在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)

我使用os.pathpython中的模块遍历每个文件。

        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'),现在我的问题是如何从这个字典中检索2ndor3rd元素?我试过print signatures[key][1]但没有运气

4

1 回答 1

1

它应该只是:

for key, value in signatures.iteritems():
    if value is not None:
        mod_time, hash = value[1:] 
于 2012-10-16T03:34:43.280 回答