Why is WindowsError when deleting a temporary file?

  • I created a temporary file.
  • Added some data to the created file.
  • Saved and then trying to delete it.

But I get it WindowsError. I closed the file after editing it. How to 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'
+3
source share
3 answers

In the documentation:

mkstemp () returns the tuple containing the OS level descriptor to an open file (which os.open () will return) and the absolute path to this file in that order. New in version 2.3.

, mkstemp , . , - ( ).

python, :

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

.

+10

. :

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

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

0
source

Source: https://habr.com/ru/post/1718442/


All Articles