如何解决在Python 3.8中使用大输入输出文件散列单词列表
我是编码的初学者,正尝试构建一个将txt文件作为输入,对其进行哈希处理并输出到每个行中都包含“ string:hashedstring”的另一个txt文件的脚本。该代码工作正常。我现在面临的问题是,如果输入文件很大,它将消耗所有RAM并杀死它。我尝试使用块,但无法弄清楚如何在多行输入和输出中使用它。 关于代码的其他部分,除了此处的主要主题之外,任何其他建议都将受到欢迎,因为我只是从此开始。谢谢。
import argparse
import hashlib
import os
import sys
def sofia_hash(msg):
h = ""
m = hashlib.md5()
m.update(msg.encode('utf-8'))
msg_md5 = m.digest()
for i in range(8):
n = (msg_md5[2*i] + msg_md5[2*i+1]) % 0x3e
if n > 9:
if n > 35:
n += 61
else:
n += 55
else:
n += 0x30
h += chr(n)
return h
top_parser = argparse.ArgumentParser(description='Sofiamass')
top_parser.add_argument('input',action="store",type=argparse.FileType('r',encoding='utf8'),help="Set input file")
top_parser.add_argument('output',help="Set output file")
args = top_parser.parse_args()
sofiainput = args.input.read().splitlines()
a = 0
try:
while a < len(sofiainput):
target_sofiainput = sofiainput[a]
etarget_sofiainput = (target_sofiainput).encode('utf-8')
try:
sofia_pass = sofia_hash(target_sofiainput)
x = True
except KeyboardInterrupt:
print ("\n[---]exiting now[---]")
if x == True:
with open(args.output,'a') as sofiaoutput:
sofiaoutput.write(str(target_sofiainput) + ":" + str(sofia_pass) + "\n")
elif x == False:
print('error')
a += 1
except KeyboardInterrupt:
print ("\n[---]exiting now[---]")
except AttributeError:
pass
解决方法
使用 open 命令打开文件时,它将创建一个称为文件处理程序的对象。因此,当您这样做时:
with open('filepath.txt','r') as f:
for line in f:
print(line)
它仅将您正在使用的当前行保留在RAM中,从而实现您使用尽可能少的RAM的目标。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。