[英]Python IO replace/overwrite text-file with hashcode
I need to overwrite each line of a (txt) file in python with (first 10 digits of) it's hashcode. 我需要用其哈希码(前10位数字)覆盖python中(txt)文件的每一行。
I'm having troubles with the writing part ( I can print it but not write it). 我在书写部分上遇到麻烦(我可以打印但不能书写)。 the old part of the file('x) should be overwritten with the new part(the hash).
文件的旧部分('x)应该被新的部分(哈希)覆盖。
[FAIL]
File passwords.txt should be transformed from ['x']
to ['2d711642b7']
[FAIL]
文件passwords.txt应该从['x']
为['2d711642b7']
Expected value: ['2d711642b7']
Actual value: ['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)
You can use fileinput and open the file in inplace
mode. 您可以使用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,
Example input: 输入示例:
x
y
z
becomes: 变为:
2d711642b7
a1fce43638
594e519ae4
PS : As it turns out, inplace is not actually inplace. PS:事实证明,就地实际上不是就地。 Under the hood, a copy of the original file is created.
在后台,将创建原始文件的副本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.