当输出结果到文件时,如何解决“ValueError:关闭文件上的I / O操作”?

问题描述 投票:0回答:1

我有一段代码使用SHA256算法将电子邮件地址转换为HASH。运行代码时,会显示预期的结果,但是当我尝试输出结果时 - 我收到错误:ValueError:关闭文件的I / O操作

import os
import hashlib

with open("emails.txt", "r") as text:
    for line in text.readlines():
        line = line.rstrip("\n")

        m = hashlib.sha256(line)
        print(m.hexdigest())

with open("Output.txt", "w") as text_file:
    for row in text:
        print row
        text_file.write("%s\n" % str(row))

任何人都可以帮助我将所有结果都收到外部文件?

python-2.7 output sha256
1个回答
0
投票

由于行for row in text:,你试图循​​环text,在脚本的这一点是一个封闭的文件。你可以这样构造代码:

import os
import hashlib

with open("emails.txt", "r") as text:
    with open("Output.txt", "w") as text_file:
        for line in text.readlines():
            line = line.rstrip("\n")
            m = hashlib.sha256(line.encode()).hexdigest() 
            print m
            print line
            text_file.write("%s:%s\n" % (str(line), m))
© www.soinside.com 2019 - 2024. All rights reserved.