Unable to delete file created by `tempfile.mkstemp ()` on Windows

Here is my sample code:

import os from tempfile import mkstemp fname = mkstemp(suffix='.txt', text=True)[1] os.remove(fname) 

When I run it on my Linux, it works fine. But when I run it on my Windows XP using Python 3.4.4, it found the following error:

 Traceback (most recent call last): File "C:\1.py", line 5, in <module> os.remove(fname) PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'C:\\DOCUME~1\\IEUser\\LOCALS~1\\Temp\\tmp3qv6ppcf.txt' 

However, when I use tempfile.NamedTemporaryFile() to create a temporary file and close it, it is automatically deleted.

Why can't Windows delete files created using mkstemp ? Where am I doing wrong?

+5
source share
1 answer

From the documentation :

Creates a temporary file in the most secure manner. [...]

[...]

mkstemp() returns the tuple containing the OS level descriptor to an open file (which os.open() will return) and the absolute path to this file in that order.

 fd, fname = mkstemp(suffix='.txt', text=True) os.close(fd) os.remove(fname) 
+10
source

Source: https://habr.com/ru/post/1240316/


All Articles