David C
David C

Reputation: 7484

Python OSError: Too many open files

I'm using Python 2.7 on Windows XP.

My script relies on tempfile.mkstemp and tempfile.mkdtemp to create a lot of files and directories with the following pattern:

_,_tmp = mkstemp(prefix=section,dir=indir,text=True)

<do something with file>

os.close(_)

Running the script always incurs the following error (although the exact line number changes, etc.). The actual file that the script is attempting to open varies.

OSError: [Errno 24] Too many open files: 'path\\to\\most\\recent\\attempt\\to\\open\\file'

Any thoughts on how I might debug this? Also, let me know if you would like additional information. Thanks!

EDIT:

Here's an example of use:

out = os.fdopen(_,'w')
out.write("Something")
out.close()

with open(_) as p:
    p.read()

Upvotes: 2

Views: 2531

Answers (2)

vsh
vsh

Reputation: 160

You probably don't have the same value stored in _ at the time you call os.close(_) as at the time you created the temp file. Try assigning to a named variable instead of _.

If would help you and us if you could provide a very small code snippet that demonstrates the error.

Upvotes: 3

mgilson
mgilson

Reputation: 309929

why not use tempfile.NamedTemporaryFile with delete=False? This allows you to work with python file objects which is one bonus. Also, it can be used as a context manager (which should take care of all the details making sure the file is properly closed):

with tempfile.NamedTemporaryFile('w',prefix=section,dir=indir,delete=False) as f:
     pass #Do something with the file here.

Upvotes: 2

Related Questions