Python write in mkstemp() file

前端 未结 3 2376
鱼传尺愫
鱼传尺愫 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条回答
  •  心在旅途
    2021-02-20 02:13

    The answer by smarx opens the file by specifying path. It is, however, easier to specify fd instead. In that case the context manager closes the file descriptor automatically:

    from tempfile import mkstemp
    
    fd, path = mkstemp()
    
    # use a context manager to open (and close) file descriptor fd (which points to path)
    with open(fd, 'w') as f:
        f.write('TEST\n')
    
    # This causes the file descriptor to be closed automatically
    

提交回复
热议问题