Why is the WindowsError while deleting the temporary file?

梦想的初衷 提交于 2019-12-22 10:05:48

问题


  1. I have created a temporary file.
  2. Added some data to the file created.
  3. Saved it and then trying to delete it.

But I am getting WindowsError. I have closed the file after editing it. How do I check which other process is accessing the file.

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'

回答1:


From the 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.

So, mkstemp returns both the OS file handle to and the filename of the temporary file. When you re-open the temp file, the original returned file handle is still open (no-one stops you from opening twice or more the same file in your program).

If you want to operate on that OS file handle as a python file object, you can:

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

and then continue with your normal code.




回答2:


The file is still open. Do this:

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



回答3:


I believe you need to release the fptr to close the file cleanly. Try setting fptr to None.



来源:https://stackoverflow.com/questions/1470350/why-is-the-windowserror-while-deleting-the-temporary-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!