Python write in mkstemp() file

前端 未结 3 2375
鱼传尺愫
鱼传尺愫 2021-02-20 01:26

I am creating a tmp file by using :

from tempfile import mkstemp

I am trying to write in this file :

tmp_file = mkstemp()
file          


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-02-20 02:14

    This example opens the Python file descriptor with os.fdopen to write cool stuff, then close it (at the end of the with context block). Other non-Python processes can use the file. And at the end, the file is deleted.

    import os
    from tempfile import mkstemp
    
    fd, path = mkstemp()
    
    with os.fdopen(fd, 'w') as fp:
        fp.write('cool stuff\n')
    
    # Do something else with the file, e.g.
    # os.system('cat ' + path)
    
    # Delete the file
    os.unlink(path)
    

提交回复
热议问题