How to use tempfile.NamedTemporaryFile()?

后端 未结 1 1501
忘了有多久
忘了有多久 2021-02-06 21:01

I\'m working on a Python script that needs to create about 50 distinct temporary files, which are all appended frequently during the course of the script and merged at the end.

相关标签:
1条回答
  • 2021-02-06 21:39

    "That name can be retrieved from the name member of the file object."

    means that you can get the name of the temporary file created like so:

    In [4]: import tempfile
    
    In [5]: tf = tempfile.NamedTemporaryFile()  
    In [6]: tf.name  # retrieve the name of the temp file just created
    Out[6]: 'c:\\blabla\\locals~1\\temp\\tmptecp3i'
    

    Note: By default the file will be deleted when it is closed. However, if the delete parameter is False, the file is not automatically deleted. See the Python docs on this for more information.

    Since you can retrieve the name of each of the 50 temp files you want to create, you can save them, e.g., in a list, before you use them again later (as you say). Just be sure to set the delete value accordingly so that the files don't disappear when you close them (in case you plan to close, and then later reopen them).

    I explained how to create temporary filenames in more detail here Best way to generate random file names in Python

    0 讨论(0)
提交回复
热议问题