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)))
Lets have a deeper look at your code.
First you create your temp file
f = tempfile.NamedTemporaryFile(mode='w+t', delete=True)
n = f.name
print('Does exist? : {0}'.format(os.path.exists(n)))
and this output
Does exist? : True
so there is nothing to worry about. Then in the next statements
f.close()
print('Does exist? : {0}'.format(os.path.exists(n)))
you are closing the file and actually the file gets deleted, because you are getting the following output:
Does exist? : False
Afterwards however you are recreating your file via
subprocess.run(['nano', n])
with open(n) as f:
print (f.read())
so this is why afterwards the command
print('Does exist? : {0}'.format(os.path.exists(n)))
returns
Does exist? : True
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.