views:

167

answers:

3
  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'
A: 

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

whatnick
Nope. That is not working.
Vijayendra Bapte
+1  A: 

The file is still open. Do this:

fh, filename = tempfile.mkstemp()
...
os.close(fh)
os.remove(filename)
Nick D
Yep. That worked. Btw, what is the use of file handle?
Vijayendra Bapte
@Vijayendra Bapte, there are file descriptor operations in the os module that you can use it.
Nick D
+2  A: 

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.

ΤΖΩΤΖΙΟΥ
Oh. Thanks for the explanation.
Vijayendra Bapte