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

D

Dani

Is it correct that low-level file handles are not being closed after
doing

fd = open(filepath)
fd.close()

If so, what is the rationale?

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.

A workaround seems to be

os_fd = os.open(filepath)
fd = os.fdopen(os_fd)
os.close(os_fd)
 
C

Clovis Fabricio

Hello Dani,

2009/12/17 Dani said:
Is it correct that low-level file handles are not being closed after
doing
fd = open(filepath)
fd.close()
If so, what is the rationale?

No, it is incorrect. I tested that exact snippet here and it correctly
closes the file. I can move the file around just after that.

There must be something wrong elsewhere on your code.

That said, you could use the "with" statement in python >2.5 to make it clearer:

with open(filepath) as fd:
# ... do stuff with fd ...

The file will be closed at the end of the with block.

nosklo
 
T

Tim Chase

Dani said:
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.

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

back to Cmd window #2C:\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
 
D

Dani

No, it is incorrect. I tested that exact snippet here and it correctly
closes the file. I can move the file around just after that.

Yes, indeed. Sorry for not getting my facts straight and thank you for
testing. Part of the code *was* holding a low-level file handle.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,731
Messages
2,569,432
Members
44,832
Latest member
GlennSmall

Latest Threads

Top