How do I persist to disk a temporary file using Python?

前端 未结 4 2031
难免孤独
难免孤独 2021-02-02 09:35

I am attempting to use the \'tempfile\' module for manipulating and creating text files. Once the file is ready I want to save it to disk. I thought it would be as simple as usi

4条回答
  •  粉色の甜心
    2021-02-02 10:16

    The file you create with TemporaryFile or NamedTemporaryFile is automatically removed when it's closed, which is why you get an error. If you don't want this, you can use mkstemp instead (see the docs for tempfile).

    >>> import tempfile, shutil, os
    >>> fd, path = tempfile.mkstemp()
    >>> os.write(fd, 'foo')
    >>> os.close(fd)
    >>> shutil.copy(path, 'bar.txt')
    >>> os.remove(path)
    

提交回复
热议问题