30

On my machine Linux machine ulimit -n gives 1024. This code:

from tempfile import mkstemp

for n in xrange(1024 + 1):
    f, path = mkstemp()    

fails at the last line loop with:

Traceback (most recent call last):
  File "utest.py", line 4, in <module>
  File "/usr/lib/python2.7/tempfile.py", line 300, in mkstemp
  File "/usr/lib/python2.7/tempfile.py", line 235, in _mkstemp_inner
OSError: [Errno 24] Too many open files: '/tmp/tmpc5W3CF'
Error in sys.excepthook:
Traceback (most recent call last):
  File "/usr/lib/python2.7/dist-packages/apport_python_hook.py", line 64, in apport_excepthook
ImportError: No module named fileutils

It seems like I've opened to many files - but the type of f and path are simply int and str so I'm not sure how to close each file that I've opened. How do I close the files from tempfile.mkstemp?

Hooked
  • 84,485
  • 43
  • 192
  • 261

3 Answers3

33

Since mkstemp() returns a raw file descriptor, you can use os.close():

import os
from tempfile import mkstemp

for n in xrange(1024 + 1):
    f, path = mkstemp()
    # Do something with 'f'...
    os.close(f)
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
17
import tempfile
import os
for idx in xrange(1024 + 1):
    outfd, outsock_path = tempfile.mkstemp()
    outsock = os.fdopen(outfd,'w')
    outsock.close()
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • 10
    Just to explain a bit. mkstemp() returns a unix file descriptor, so you to work with it you need either open it using fdopen or use the os close function: os.close() – turtlebender Mar 30 '12 at 13:48
5

Use os.close() to close the file descriptor:

import os
from tempfile import mkstemp

# Open a file
fd, path = mkstemp()  

# Close opened file
os.close( fd )
Mariusz Jamro
  • 30,615
  • 24
  • 120
  • 162