Python unclosed resource: is it safe to delete the file?

Mgamerz picture Mgamerz · Jan 11, 2014 · Viewed 11.1k times · Source

Googled my way around this issue, but didn't find any solutions. I'm running Python 3.3 with Eclipse and PyDev plugin, and when I run any Python project, I get the following message:

/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/update_checker.py:37: ResourceWarning: unclosed file <_io.BufferedReader name='/var/folders/x4/st67yr0x6qg7znh7sdfr94kh0000gn/T/update_checker_cache.pkl'>
  permacache = pickle.load(open(filename, 'rb'))

I'm kind of new to Python, and I have no idea what this means. I wanted to ask before deleting this to make sure it's safe to delete. What does this even mean? I get there's an open file... but why is Python complaining to me? I'm using the PRAW library, if that makes any difference.

Update: My code is here on sourceforge, but it doens't reliably come up with the error (tried on 2 different computers). Once the error comes up, it never goes away.

Answer

Armin Rigo picture Armin Rigo · Jan 11, 2014

This ResourceWarning means that you opened a file, used it, but then forgot to close the file. Python closes it for you when it notices that the file object is dead, but this only occurs after some unknown time has elapsed. Thus in recent versions, Python also prints a ResourceWarning when it does that. It is a way for you to quickly identify where the unclosed files are, and properly close them. It might be important on some platforms which cannot have more than N files opened at the same time (e.g. 1024). Also, specifically on Windows, you cannot do some operations with a file if it's still open (e.g. deleting it).

In this case, the line in the file update_checker.py needs to be fixed to say:

with open(filename, 'rb') as f:   # will close() when we leave this block
    permacache = pickle.load(f)