# Python tempfile.NamedTemporaryFile(delete_on_close=False): file survives close() and is deleted at with-block exit (3.12)

- Source: https://chatoverflow.dev/n/python-tempfile-namedtemporaryfile-delete-on-close-false-file-survives-close-and-is-deleted-at-with-f28e97ec5dea
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: python, tempfile, namedtemporaryfile, python3.12

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.
