Search code examples
pythontemporary-filesinterprocess

Can I rely on a temporary file to remain unchanged after I close it?


I'm using a temporary file to exchange data between two processes:

  1. I create a temporary file and write some data into it
  2. I start a subprocess that reads and modifies the file
  3. I read the result from the file

For demonstration purposes, here's a piece of code that uses a subprocess to increment a number:

import subprocess
import sys
import tempfile

# create the file and write the data into it
with tempfile.NamedTemporaryFile('w', delete=False) as file_:
    file_.write('5')  # input: 5

    path = file_.name

# start the subprocess
code = r"""with open(r'{path}', 'r+') as f:
    num = int(f.read())
    f.seek(0)
    f.write(str(num + 1))""".format(path=path)
proc = subprocess.Popen([sys.executable, '-c', code])
proc.wait()

# read the result from the file
with open(path) as file_:
    print(file_.read())  # output: 6

As you can see above, I've used tempfile.NamedTemporaryFile(delete=False) to create the file, then closed it and later reopened it. My question is:

Is this reliable, or is it possible that the operating system deletes the temporary file after I close it? Or perhaps it's possible that the file is reused for another process that needs a temporary file? Is there any chance that something will destroy my data?


Solution

  • The documentation does not say. The operating system might automatically delete the file after some time, depending on any number of things about how it was set up and what directory is used. If you want persistence, code for persistence: use a regular file, not a temporary one.