我有一个包含很多字符串的文件。我试图分别计算这些字符串的sha1散列并存储它们

import hashlib
inp = open("inp.txt" , "r")
outputhash  = open("outputhashes.txt", "w")
for eachpwd in inp:
    sha_1 = hashlib.sha1()
    sha_1.update(eachpwd)
    outputhash.write(sha_1.hexdigest())
    outputhash.write("\n")

我面临的问题是,一旦一个字符串sha1被计算出来,下一个字符串就会被附加(我觉得这就是为什么我没有得到正确的散列值),它的散列值也会被计算出来。因此我没有得到正确的散列值。我是巨蟒的新手。我知道该怎么做,但不知道该怎么做。你能给我指出正确的方向吗?

最佳答案

您正在迭代一个文件,该文件将返回行,包括行终止符(字符串末尾的一个\n字符)。
您应该删除它:

import hashlib
inp = open("inp.txt" , "r")
outputhash  = open("outputhashes.txt", "w")
for line in inp:            # Change this
    eachpwd = line.strip()  # Change this

    # Add this to understand the problem:
    print repr(line)

    sha_1 = hashlib.sha1()
    sha_1.update(eachpwd)
    outputhash.write(sha_1.hexdigest())
    outputhash.write("\n")

08-07 01:59