how to use tempfile.NamedTemporaryFile() in python

前端 未结 3 1835
我寻月下人不归
我寻月下人不归 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:18

    Here is a useful context manager for this. (In my opinion, this functionality should be part of the Python standard library.)

    # python2 or python3
    import contextlib
    import os
    
    @contextlib.contextmanager
    def temporary_filename(suffix=None):
      """Context that introduces a temporary file.
    
      Creates a temporary file, yields its name, and upon context exit, deletes it.
      (In contrast, tempfile.NamedTemporaryFile() provides a 'file' object and
      deletes the file as soon as that file object is closed, so the temporary file
      cannot be safely re-opened by another library or process.)
    
      Args:
        suffix: desired filename extension (e.g. '.mp4').
    
      Yields:
        The name of the temporary file.
      """
      import tempfile
      try:
        f = tempfile.NamedTemporaryFile(suffix=suffix, delete=False)
        tmp_name = f.name
        f.close()
        yield tmp_name
      finally:
        os.unlink(tmp_name)
    
    # Example:
    with temporary_filename() as filename:
      os.system('echo Hello >' + filename)
      assert 6 <= os.path.getsize(filename) <= 8  # depending on text EOL
    assert not os.path.exists(filename)
    

提交回复
热议问题