Search code examples
pythonwindows-xppython-2.7

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()

Solution

  • 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.