I was experimenting with opening text editors from my python script and I noticed something that apparently contradicts my understanding of the documentation of tempfile.
My experiment started out with Alex Martelli's answer.
My code -
import os
import tempfile
import subprocess
f = tempfile.NamedTemporaryFile(mode='w+t', delete=True)
n = f.name
print('Does exist? : {0}'.format(os.path.exists(n)))
f.close()
print('Does exist? : {0}'.format(os.path.exists(n)))
subprocess.run(['nano', n])
with open(n) as f:
print (f.read())
print('Does exist? : {0}'.format(os.path.exists(n)))
OUTPUT:
Does exist? : True
Does exist? : False
Hello from temp file.
Does exist? : True
In the code, I explicitly call close
on the file object declared with delete=True
, however even then I am able to write and read contents to it. I don't understand why this is happening.
According to the docs-
If delete is true (the default), the file is deleted as soon as it is closed.
If calling close
deletes the file then I SHOULD NOT be able to write and then read it. But it displays the correct contents of the file that you enter when nano
executes. And like a tempfile, the file is not visible in the directory where I opened the terminal and ran the script.
What is even more strange is that os.path.exists
works correctly for the first two times and possibly incorrectly for the third time.
Am I missing something here?
Additional Experiment:
If I run the following code then I can clearly see the file created. But that doesn't happen in the original code.
n = '.temp'
subprocess.run(['nano', n])
with open(n) as f:
print (f.read())
print('Does exist? : {0}'.format(os.path.exists(n)))