I have the following code, and am getting an error: I/O operation on a closed file despite having opened the file.
我有下面的代码,并且正在得到一个错误:尽管打开了文件,但在一个关闭的文件上执行I/O操作。
I am creating a .txt file and writing values of a dictionary to the .txt file, then closing the file.
我正在创建一个.txt文件,并将字典的值写入.txt文件,然后关闭该文件。
After that I am trying to print the SHA256 digest for the file created.
在此之后,我将尝试为创建的文件打印SHA256摘要。
sys.stdout = open('answers.txt', 'w')
for key in dictionary:
print(dictionary[key])
sys.stdout.close()
f = open('answers.txt', 'r+')
#print(hashlib.sha256(f.encode('utf-8')).hexdigest())
m = hashlib.sha256()
m.update(f.read().encode('utf-8'))
print(m.hexdigest())
f.close()
Why am I getting this error?
为什么会出现这个错误?
Traceback (most recent call last):
File "filefinder.py", line 97, in <module>
main()
File "filefinder.py", line 92, in main
print(m.hexdigest())
ValueError: I/O operation on closed file.
1
Here, you override sys.stdout
to point to your opened file:
在这里,你覆盖系统。stdout指向您打开的文件:
sys.stdout = open('answers.txt', 'w')
Later, when you try to print to STDOUT
sys.stdout
is still pointing to the (now closed) answers.txt
file:
稍后,当您试图打印到STDOUT系统时。stdout仍然指向(现在已经关闭的)答案。txt文件:
print(m.hexdigest())
I don't see any reason to override sys.stdout
here. Instead, just pass a file
option to print()
:
我看不出有什么理由推翻sys。stdout。相反,只需通过一个文件选项来打印():
answers = open('answers.txt', 'w')
for key in dictionary:
print(dictionary[key], file=answers)
answers.close()
Or, using the with
syntax that automatically closes the file:
或者,使用带有自动关闭文件的语法:
with open('answers.txt', 'w') as answers:
for key in dictionary:
print(dictionary[key], file=answers)
1
You have been overwriting sys.stdout
with a file handle. As soon as you close it, you can write to it anymore. Since print()
tries to write to sys.stdout
it will fail.
你一直在写系统。使用一个文件句柄进行stdout。一旦你关闭它,你就可以再给它写信了。因为print()尝试写到sys。stdout将失败。
You should try opening the file in a different mode (w+
for example), use a StringIO
or copy the original sys.stdout
and restore it later.
您应该尝试以不同的模式打开文件(例如w+),使用StringIO或复制原始的sys。stdout并在稍后恢复它。
本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2016/12/02/bfba784a149076bb1633d9cdeaf4302f.html。