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

2024-10-01 09:30:38 发布

您现在位置:Python中文网/ 问答频道 /正文

  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'

Tags: 文件数据import编辑osfilenametempfileprocess
3条回答

文件仍处于打开状态。执行以下操作:

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

documentation

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. New in version 2.3.

因此,mkstemp同时将OS文件句柄返回到临时文件的文件名。重新打开临时文件时,原始返回的文件句柄仍处于打开状态(没有人阻止您在程序中打开两个或多个相同的文件)。

如果要将该OS文件句柄作为python文件对象进行操作,可以:

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

然后继续你的正常代码。

我相信您需要释放fptr才能干净地关闭文件。尝试将fptr设置为None。

相关问题 更多 >