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

后端 未结 6 1545
谎友^
谎友^ 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')
    
    0 讨论(0)
  • 2021-02-01 01:04

    You forgot to specify the open mode ('w') in fdopen(). The default is 'r', causing the write() call to fail.

    I think mkstemp() creates the file for reading only. Calling fdopen with 'w' probably reopens it for writing (you can reopen the file created by mkstemp).

    0 讨论(0)
  • 2021-02-01 01:07

    What's your goal, here? Is tempfile.TemporaryFile inappropriate for your purposes?

    0 讨论(0)
  • 2021-02-01 01:10
    temp = tempfile.NamedTemporaryFile(delete=False)
    temp.file.write('foo\n')
    temp.close()
    
    0 讨论(0)
  • 2021-02-01 01:12

    I can't comment on the answers, so I will post my comment here:

    To create a temporary file for write access you can use tempfile.mkstemp and specify "w" as the last parameter, like:

    f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'...
    os.write(f[0], "write something")
    
    0 讨论(0)
  • 2021-02-01 01:18

    You can use

    os.write(tup[0], "foo\n")
    

    to write to the handle.

    If you want to open the handle for writing you need to add the "w" mode

    f = os.fdopen(tup[0], "w")
    f.write("foo")
    
    0 讨论(0)
提交回复
热议问题