Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I close the files from tempfile.mkstemp?

Tags:

python

ulimit

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?

like image 405
Hooked Avatar asked Mar 30 '12 13:03

Hooked


People also ask

What is Tempfile Mkstemp?

tempfile. mkstemp (suffix=None, prefix=None, dir=None, text=False) Creates a temporary file in the most secure manner possible. There are no race conditions in the file's creation, assuming that the platform properly implements the os. O_EXCL flag for os.

How do I delete temp files in Python?

gettempdir() to get the directory where all the temp files are stored. After running the program, if you go to temp_dir (which is /tmp in my case – Linux), you can see that the newly created file 3 is not there. This proves that Python automatically deletes these temporary files after they are closed.

What does TMP mean in Python?

Introduction. Temporary files, or "tempfiles", are mainly used to store intermediate information on disk for an application. These files are normally created for different purposes such as temporary backup or if the application is dealing with a large dataset bigger than the system's memory, etc.


2 Answers

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) 
like image 86
Frédéric Hamidi Avatar answered Sep 18 '22 11:09

Frédéric Hamidi


import tempfile import os for idx in xrange(1024 + 1):     outfd, outsock_path = tempfile.mkstemp()     outsock = os.fdopen(outfd,'w')     outsock.close() 
like image 35
unutbu Avatar answered Sep 20 '22 11:09

unutbu