无法删除由 `tempfile.mkstemp()` 在 Windows 上创建的文件
Can't remove a file which created by `tempfile.mkstemp()` on Windows
这是我的示例代码:
import os
from tempfile import mkstemp
fname = mkstemp(suffix='.txt', text=True)[1]
os.remove(fname)
当我 运行 它在我的 Linux 上时,它工作正常。但是当我 运行 在我的 Windows XP 上使用 Python 3.4.4 时,它引发了以下错误:
Traceback (most recent call last):
File "C:.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'
但是,当我使用 tempfile.NamedTemporaryFile()
创建临时文件并关闭它时,它会自动删除。
为什么 Windows 无法删除 mkstemp
创建的文件?我哪里做错了?
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)
这是我的示例代码:
import os
from tempfile import mkstemp
fname = mkstemp(suffix='.txt', text=True)[1]
os.remove(fname)
当我 运行 它在我的 Linux 上时,它工作正常。但是当我 运行 在我的 Windows XP 上使用 Python 3.4.4 时,它引发了以下错误:
Traceback (most recent call last):
File "C:.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'
但是,当我使用 tempfile.NamedTemporaryFile()
创建临时文件并关闭它时,它会自动删除。
为什么 Windows 无法删除 mkstemp
创建的文件?我哪里做错了?
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)