how to use tempfile.NamedTemporaryFile() in python

前端 未结 3 1839
我寻月下人不归
我寻月下人不归 2021-02-01 01:44

I want to use tempfile.NamedTemporaryFile() to write some contents into it and then open that file. I have written following code:

tf = tempfile.Nam         


        
3条回答
  •  北荒
    北荒 (楼主)
    2021-02-01 02:13

    You can also use it with a context manager so that the file will be closed/deleted when it goes out of scope. It will also be cleaned up if the code in the context manager raises.

    import tempfile
    with tempfile.NamedTemporaryFile() as temp:
        temp.write('Some data')
        temp.flush()
    
        # do something interesting with temp before it is destroyed
    

提交回复
热议问题