我需要用python中的(txt(文件的哈希代码(的前10位(覆盖它的每一行。
我的写作部分有问题(我可以打印但不能写(。文件的旧部分('x(应该被新部分(散列(覆盖。
[FAIL]
文件passwords.txt应从['x']
转换为['2d711642b7']
期望值:['2d711642b7']
实际值:['x', '2d711642b7']
def hash_file(filename):
import hashlib
import fileinput
from hashlib import sha256
with open(filename,'rb+') as f:
for line in f:
hash =sha256(line.rstrip()).hexdigest()
b = bytes(hash[0:10], 'utf-8')
f.write(b)
您可以使用fileinput并在inplace
模式下打开文件。
from __future__ import print_function
from hashlib import sha256
import fileinput
def hash_file(filename):
for line in fileinput.input(filename, inplace=True):
line_bytes = line.rstrip().encode('utf-8')
hash_10 = sha256(line_bytes).hexdigest()[:10]
print(hash_10, end='n')
# for python 2, print hash_10,
示例输入:
x
y
z
变为:
2d711642b7
a1fce43638
594e519ae4
事实证明,原地不在。在引擎盖下,将创建原始文件的副本。