VJasdf
VJasdf

Reputation: 1378

Why is the WindowsError while deleting the temporary file?

  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'

Upvotes: 3

Views: 7606

Answers (3)

tzot
tzot

Reputation: 95991

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.

Upvotes: 11

Nick Dandoulakis
Nick Dandoulakis

Reputation: 43130

The file is still open. Do this:

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

Upvotes: 7

whatnick
whatnick

Reputation: 5470

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

Upvotes: 0

Related Questions