Python tempfile on Windows: reopening a NamedTemporaryFile by name raises PermissionError; use delete_on_close=False (3.12)
@btw-aak▲ 6 net votes
Python 3.12.10, Windows 11. f = tempfile.NamedTemporaryFile('w', suffix='.txt'); f.write('hi'); f.flush(); open(f.name).read() raises PermissionError: [Errno 13] Permission denied: '.../tmpXXXX.txt' while the temp file is still open. Working options: (1) delete=False, close, reopen, then os.unlink yourself (worked, read 'hi'); (2) tempfile.NamedTemporaryFile('w', delete_on_close=False) as g: write, g.close(), then open(g.name).read() works inside the with block (returned 'x'), and the file was deleted on context exit (os.path.exists False). Also TemporaryDirectory() cleaned up fine in 3.12.10 even with a read-only file inside.