1
import gc
import os

gc.disable()

open('tmp.txt', 'w').close()

class A:
    def __init__(self):
        self.fo = open('tmp.txt')

a = A()

os.remove('tmp.txt')

When I execute the script, I got a PermissionError: [WinError 32].Then I try this:

import gc
import os

gc.disable()

open('tmp.txt', 'w').close()

class A:
    def __init__(self):
        self.fo = open('tmp.txt')

a = A()

# or a = None
del a

os.remove('tmp.txt')

Although it succeeded this time, but I don't know the reason. Could you tell me why?

My python version is 3.5.2.

martineau
  • 119,623
  • 25
  • 170
  • 301
Jeffery
  • 307
  • 1
  • 10

1 Answers1

2

on windows you cannot remove a file if some program has a handle on it.

When you deleted your instance, you manually/forcefully garbage collected the handle (since no other object had a reference on a), and closing the file, which explains that it worked.

also see how to release used memory immediately in python list? where it's explained that

del a

or

a = None

immediately frees the memory of a if no other object holds a reference on it.

Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
  • I have called the gc.disable to disable garbage collected, but it still works.I s my approach wrong? – Jeffery Dec 07 '16 at 09:27
  • but if you explicitly call `del`, the object is deleted even if garbage collector is not running. This is a manual garbage collection. Maybe I answered too fast. What do you want to achieve. Try `a=None` with gc off, you could have a different result. – Jean-François Fabre Dec 07 '16 at 09:28
  • when I assign None to `a` instead of `del` it, it still works. Is this a garbage collection? – Jeffery Dec 07 '16 at 09:34
  • seems so: http://stackoverflow.com/questions/12417498/how-to-release-used-memory-immediately-in-python-list/12417903#12417903 – Jean-François Fabre Dec 07 '16 at 09:38
  • Specifically, on Windows you can't remove a file (i.e. set its delete disposition) unless all open instances share delete access. Python's `open` does not share delete access. – Eryk Sun Dec 08 '16 at 04:01