Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't remove a file which created by `tempfile.mkstemp()` on Windows

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?

like image 838
Remi Crystal Avatar asked Jan 11 '16 08:01

Remi Crystal


People also ask

Why I cant delete temp files?

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.

What is Tempfile Mkstemp return?

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.


1 Answers

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 by os.open()) and the absolute pathname of that file, in that order.

fd, fname = mkstemp(suffix='.txt', text=True)
os.close(fd)
os.remove(fname)
like image 132
Ignacio Vazquez-Abrams Avatar answered Sep 23 '22 13:09

Ignacio Vazquez-Abrams