Py学习  »  Python

用Python从文件的2个元素创建哈希表

TNN.309 • 3 年前 • 1229 次点击  

我正在尝试组合一个txt文件的每两个元素,并使用Python对其进行哈希,以创建一个哈希表。我的代码如下:

import hashlib
def SHA1_hash(string):
    hash_obj = hashlib.sha1(string.encode())
    return(hash_obj.hexdigest())
with open("/Users/admin/Downloads/Project_files/dictionary.txt") as f:
    text_file = open("/Users/admin/Downloads/Project_files/text_combined.txt", "w",encoding = 'utf-8')
    for i in f.readlines():
        for j in f.readlines():
            text_c = i.strip() + j.strip()
            n = text_file.write(SHA1_hash(text_c) + "\n")
    text_file.close()

文件大小为64KB(超过5700行)。我试图运行代码,但它不工作,也没有显示任何错误。目标文件(text_combined.txt)也没有任何内容。我能问一下我做得对还是错吗?

我对Python和编程都是新手,所以如果我问了一些不好的问题,请原谅。非常感谢。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132032
 
1229 次点击  
文章 [ 1 ]  |  最新文章 3 年前
Barmar
Reply   •   1 楼
Barmar    3 年前

第二个 f.readlines() 没有要读取的内容,因为您已经读取了整个文件。

将文件读入列表变量,然后遍历列表。

with open("/Users/admin/Downloads/Project_files/dictionary.txt") as f, open("/Users/admin/Downloads/Project_files/text_combined.txt", "w",encoding = 'utf-8') as textfile:
    lines = f.readlines():
    for i in lines:
        for j in lines:
            text_c = i.strip() + j.strip()
            n = text_file.write(SHA1_hash(text_c) + "\n")