Python Temporary Files and Directories: Difference between revisions
Jump to navigation
Jump to search
Line 7: | Line 7: | ||
<code>TemporaryFile</code>, <code>NamedTemporaryFile</code> and <code>TemporaryDirectory</code> are classes that provide temporary files and directories that, in conjunction with the <code>[[Python_Context_Manager#Overview|with]]</code> reserved word, are self-deleting when we the program gets out of scope. | <code>TemporaryFile</code>, <code>NamedTemporaryFile</code> and <code>TemporaryDirectory</code> are classes that provide temporary files and directories that, in conjunction with the <code>[[Python_Context_Manager#Overview|with]]</code> reserved word, are self-deleting when we the program gets out of scope. | ||
==Auto-Deleting Temporary File== | ==Auto-Deleting Temporary File== | ||
The underlying file system file will be deleted as soon as the <code>TemporaryFile</code> object is closed. | |||
==Auto-Deleting Temporary Directory== | ==Auto-Deleting Temporary Directory== | ||
Revision as of 20:19, 13 June 2023
External
Internal
Auto-Deleting Temporary Files and Directories
TemporaryFile
, NamedTemporaryFile
and TemporaryDirectory
are classes that provide temporary files and directories that, in conjunction with the with
reserved word, are self-deleting when we the program gets out of scope.
Auto-Deleting Temporary File
The underlying file system file will be deleted as soon as the TemporaryFile
object is closed.
Auto-Deleting Temporary Directory
Temporary Files and Directories to be Deleted by the Caller
Temporary File to be Deleted by the Caller
Temporary Directory to be Deleted by the Caller
Create a named temporary file, write in it and return the name. The file is not automatically deleted after close()
, the caller will need to delete it:
import tempfile
with tempfile.NamedTemporaryFile(mode='w+t', delete=False) as t:
t.write(something)
return t.name