file.close() does not really close under Windows?

Tim Chase python.list at tim.thechases.com
Thu Dec 17 09:33:08 EST 2009


Dani wrote:
> Is it correct that low-level file handles are not being closed after
> doing
> 
>   fd = open(filepath)
>   fd.close()

no, you are not correct.

Demonstration:

Cmd window #1:

c:\temp> echo hello world > x.txt

Cmd window #2

c:\temp> python
Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit 
(Intel)] on win32
Type "help", "copyright", "credits" or "license" for more 
information.
 >>> f = file('x.txt')
 >>> f.close()
 >>> # remaining in an open python session


back to Cmd window #1
C:\temp> del x.txt
C:\temp> rem note...no error here.
C:\temp> exit

back to Cmd window #2
 >>> # quit python
 >>> ^Z
C:\temp> exit


> If so, what is the rationale?

it's not because there is no good rationale for wanting that 
behavior :)  The above was performed on XP (SP2 & SP3) with no 
issues.  I can't guarantee that MS hasn't borked something in 
Vista or Win7, but if they did, that's *their* issue, not Python's.

> This seems to result in system errors when trying to (re-)move or
> reopen "closed" files, as well as when opening (and closing) too many
> files under Windows.

As always, check your own code/environment before assuming the 
problem is with Python.  In all likelihood, you had the file open 
in another window/process and didn't remember.  Perhaps some 
background indexing process happened to hold the file open for a 
brief spell?

-tkc






More information about the Python-list mailing list