为什么删除临时文件时会出现WindowsError?

3 投票
3 回答
7587 浏览
提问于 2025-04-15 14:34
  1. 我创建了一个临时文件。
  2. 在这个文件里添加了一些数据。
  3. 保存了文件,然后想要删除它。

但是我遇到了一个WindowsError错误。我在编辑完文件后已经关闭了它。请问我该如何检查还有哪个其他程序在使用这个文件呢?

C:\Documents and Settings\Administrator>python
Python 2.6.1 (r261:67517, Dec  4 2008, 16:51:00) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import tempfile
>>> __, filename = tempfile.mkstemp()
>>> print filename
c:\docume~1\admini~1\locals~1\temp\tmpm5clkb
>>> fptr = open(filename, "wb")
>>> fptr.write("Hello World!")
>>> fptr.close()
>>> import os
>>> os.remove(filename)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
WindowsError: [Error 32] The process cannot access the file because it is being used by
       another process: 'c:\\docume~1\\admini~1\\locals~1\\temp\\tmpm5clkb'

3 个回答

0

我觉得你需要释放 fptr 这个指针,才能干净地关闭文件。试着把 fptr 设置为 None。

7

文件仍然是打开的状态。你可以这样做:

fh, filename = tempfile.mkstemp()
...
os.close(fh)
os.remove(filename)
11

来自文档的内容:

mkstemp() 会返回一个元组,里面包含一个操作系统级别的打开文件句柄(就像使用 os.open() 返回的那样)和那个文件的绝对路径名,顺序是这样的。

所以,mkstemp 会同时返回临时文件的操作系统文件句柄和文件名。当你重新打开这个临时文件时,最开始返回的文件句柄仍然是打开的(在你的程序里,没人会阻止你多次打开同一个文件)。

如果你想把这个操作系统的文件句柄当作 Python 的文件对象来使用,你可以:

>>> __, filename = tempfile.mkstemp()
>>> fptr= os.fdopen(__)

然后继续写你的正常代码。

撰写回答