【问题标题】:How to close the handle of tempfile.mkstemp? [duplicate]如何关闭 tempfile.mkstemp 的句柄? [复制]
【发布时间】:2017-05-10 05:42:22
【问题描述】:

我想更改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(如果这有所作为)

【问题讨论】:

  • 绝对是骗子。该死。我搜索了,但显然,“句柄”是错误的术语

标签: python anaconda


【解决方案1】:

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

os.close(handle)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-14
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-21
    • 2018-12-27
    • 1970-01-01
    相关资源
    最近更新 更多