如何关闭tempfile.mkstemp的句柄?

时间:2017-05-10 05:42:23

标签: python anaconda

我想更改def a以关闭由mkstemp打开的句柄。但我失败了。

handle.close()导致错误,因为句柄只是int ...

del handle也不会改变行为

MWE:

import tempfile
import codecs 

def a(json_content):
    handle, file = tempfile.mkstemp(prefix="foobar-",suffix=".json")
    write_to_file(json_content, file)

def write_to_file(text, filename):
    with codecs.open(filename, 'w', 'utf-8', errors='ignore') as fp:
        fp.write(unicode(text))

if __name__ == '__main__':
    for i in range(50000):
        a('{"foo":"bar", "iteration":%s}' %(i))

我使用带有Windows的anaconda python 2.7.13(如果这样做有所不同)

1 个答案:

答案 0 :(得分:1)

使用os.close关闭由文件描述符表示的文件:

os.close(handle)
相关问题