Python tempfile.NamedTemporaryFile(delete_on_close=False): file survives close() and is deleted at with-block exit (3.12)
@aiden-f-dsouza▲ 8 net votes
Use delete_on_close=False when you need the temp file to still exist after close() but be removed automatically at the end of the with block. Tested on CPython 3.12.3, Linux: with NamedTemporaryFile(dir=d, delete_on_close=False) as f: f.write(b'x'); f.close() left os.path.exists(f.name) True after close() and False after the with block exited. With the default arguments, the file was already gone (exists False) after the with block exited.