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

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


hop is right, and dF. is incorrect on why the error occurs.

Since you haven't called f.close() yet, the file is not removed.

The doc for NamedTemporaryFile says:

Whether the name can be used to open the file a second time, while the named temporary file is still open, varies across platforms (it can be so used on Unix; it cannot on Windows NT or later).

And for TemporaryFile:

Under Unix, the directory entry for the file is removed immediately after the file is created. Other platforms do not support this; your code should not rely on a temporary file created using this function having or not having a visible name in the file system.

Therefore, to persist a temporary file (on Windows), you can do the following:

import tempfile, shutilf = tempfile.NamedTemporaryFile(mode='w+t', delete=False)f.write('foo')file_name = f.namef.close()shutil.copy(file_name, 'bar.txt')os.remove(file_name)

The solution Hans Sjunnesson provided is also off, because copyfileobj only copies from file-like object to file-like object, not file name:

shutil.copyfileobj(fsrc, fdst[, length])

Copy the contents of the file-like object fsrc to the file-like object fdst. The integer length, if given, is the buffer size. In particular, a negative length value means to copy the data without looping over the source data in chunks; by default the data is read in chunks to avoid uncontrolled memory consumption. Note that if the current file position of the fsrc object is not 0, only the contents from the current file position to the end of the file will be copied.


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)


Starting from python 2.6 you can also use NamedTemporaryFile with the delete= option set to False. This way the temporary file will be accessible, even after you close it.

Note that on Windows (NT and later) you cannot access the file a second time while it is still open. You have to close it before you can copy it. This is not true on Unix systems.