如何从tempfile.mkstemp关闭文件?

时间:2012-03-30 13:40:47

标签: python ulimit

在我的机器上,Linux机器ulimit -n提供1024。这段代码:

from tempfile import mkstemp

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

在最后一行循环失败:

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

好像我已经打开了许多文件 - 但typef的{​​{1}}只是pathint所以我是不确定如何关闭我打开的每个文件。 如何从tempfile.mkstemp关闭文件?

3 个答案:

答案 0 :(得分:24)

由于mkstemp()返回原始文件描述符,您可以使用os.close()

import os
from tempfile import mkstemp

for n in xrange(1024 + 1):
    f, path = mkstemp()
    # Do something with 'f'...
    os.close(f)

答案 1 :(得分:14)

import tempfile
import os
for idx in xrange(1024 + 1):
    outfd, outsock_path = tempfile.mkstemp()
    outsock = os.fdopen(outfd,'w')
    outsock.close()

答案 2 :(得分:2)

使用os.close()关闭文件描述符:

import os
from tempfile import mkstemp

# Open a file
fd, path = mkstemp()  

# Close opened file
os.close( fd )