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。