Python I/O operation on a closed file, why the error? Code below
<p>I have the following code, and am getting an error:  I/O operation on a closed file despite having opened the file.</p>

<p>I am creating a .txt file and writing values of a dictionary to the .txt file, then closing the file.</p>

<p>After that I am trying to print the SHA256 digest for the file created.</p>

<pre><code>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()
</code></pre>

<p>Why am I getting this error?</p>

<pre><code>Traceback (most recent call last):
  File "filefinder.py", line 97, in &lt;module&gt;
    main()
  File "filefinder.py", line 92, in main
    print(m.hexdigest())
ValueError: I/O operation on closed file.
</code></pre>