Python - How do I convert “an OS-level handle to an open file” to a file object?

后端 未结 6 1594
谎友^
谎友^ 2021-02-01 00:57

tempfile.mkstemp() returns:

a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that fi

6条回答
  •  旧巷少年郎
    2021-02-01 01:04

    Here's how to do it using a with statement:

    from __future__ import with_statement
    from contextlib import closing
    fd, filepath = tempfile.mkstemp()
    with closing(os.fdopen(fd, 'w')) as tf:
        tf.write('foo\n')
    

提交回复
热议问题