Here's my example 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 raised 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 temp file and close it, it removed automatically.
Why Windows can't remove files created by mkstemp
? Where am I doing wrong?
If you want to delete temporary files in Windows 11, you just need to use the built-in tools, or if you're an experienced user, you can do that manually. If a file is open in another program, that might prevent you from deleting it, so you need to find the application that is using it and turn it off.
According to tempfile. mkstemp docs, mkstemp() returns a tuple containing an OS-level handle to an open file (as would be returned by os. open() ) and the absolute pathname of that file, in that order.
From the documentation:
Creates a temporary file in the most secure manner possible. [...]
[...]
mkstemp()
returns a tuple containing an OS-level handle to an open file (as would be returned byos.open()
) and the absolute pathname of that file, in that order.
fd, fname = mkstemp(suffix='.txt', text=True)
os.close(fd)
os.remove(fname)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With