无法在Windows上删除由`tempfile.mkstemp()`创建的文件

Kev*_*uan 9 python windows file-io temporary-files python-3.x

这是我的示例代码:

import os
from tempfile import mkstemp

fname = mkstemp(suffix='.txt', text=True)[1]
os.remove(fname)
Run Code Online (Sandbox Code Playgroud)

当我在Linux上运行它时,它运行正常.但是当我使用Python 3.4.4在我的Windows XP上运行它时,它引发了以下错误:

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'
Run Code Online (Sandbox Code Playgroud)

但是,当我tempfile.NamedTemporaryFile()用来创建临时文件并关闭它时,它会自动删除.

为什么Windows无法删除由mkstemp?创建的文件?我哪里做错了?

Ign*_*ams 14

文档:

尽可能以最安全的方式创建临时文件.[...]

[...]

mkstemp()将包含操作系统级句柄的元组返回到打开的文件(如将返回os.open())和该文件的绝对路径名,按此顺序.

fd, fname = mkstemp(suffix='.txt', text=True)
os.close(fd)
os.remove(fname)
Run Code Online (Sandbox Code Playgroud)