parthtamu/rag-code-assistant
0
1<!DOCTYPE html>2 3<html lang="en" data-content_root="../">4 <head>5 <meta charset="utf-8" />6 <meta name="viewport" content="width=device-width, initial-scale=1.0" /><meta name="viewport" content="width=device-width, initial-scale=1" />7<meta property="og:title" content="tempfile — Generate temporary files and directories" />8<meta property="og:type" content="website" />9<meta property="og:url" content="https://docs.python.org/3/library/tempfile.html" />10<meta property="og:site_name" content="Python documentation" />11<meta property="og:description" content="Source code: Lib/tempfile.py This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFil..." />12<meta property="og:image:width" content="1146" />13<meta property="og:image:height" content="600" />14<meta property="og:image" content="https://docs.python.org/3.15/_images/social_previews/summary_library_tempfile_40a3367c.png" />15<meta property="og:image:alt" content="Source code: Lib/tempfile.py This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFil..." />16<meta name="description" content="Source code: Lib/tempfile.py This module creates temporary files and directories. It works on all supported platforms. TemporaryFile, NamedTemporaryFile, TemporaryDirectory, and SpooledTemporaryFil..." />17<meta name="twitter:card" content="summary_large_image" />18<meta name="theme-color" content="#3776ab">19 20 <title>tempfile — Generate temporary files and directories — Python 3.15.0a6 documentation</title><meta name="viewport" content="width=device-width, initial-scale=1.0">21 22 <link rel="stylesheet" type="text/css" href="../_static/pygments.css?v=b86133f3" />23 <link rel="stylesheet" type="text/css" href="../_static/classic.css?v=234b1a7c" />24 <link rel="stylesheet" type="text/css" href="../_static/pydoctheme.css?v=89a2f22a" />25 <link rel="stylesheet" type="text/css" href="../_static/profiling-sampling-visualization.css?v=0c2600ae" />26 <link id="pygments_dark_css" media="(prefers-color-scheme: dark)" rel="stylesheet" type="text/css" href="../_static/pygments_dark.css?v=5349f25f" />27 28 <script src="../_static/documentation_options.js?v=6b7c9ff5"></script>29 <script src="../_static/doctools.js?v=9bcbadda"></script>30 <script src="../_static/sphinx_highlight.js?v=dc90522c"></script>31 <script src="../_static/profiling-sampling-visualization.js?v=9811ed04"></script>32 33 <script src="../_static/sidebar.js"></script>34 35 <link rel="search" type="application/opensearchdescription+xml"36 title="Search within Python 3.15.0a6 documentation"37 href="../_static/opensearch.xml"/>38 <link rel="author" title="About these documents" href="../about.html" />39 <link rel="index" title="Index" href="../genindex.html" />40 <link rel="search" title="Search" href="../search.html" />41 <link rel="copyright" title="Copyright" href="../copyright.html" />42 <link rel="next" title="glob — Unix style pathname pattern expansion" href="glob.html" />43 <link rel="prev" title="filecmp — File and Directory Comparisons" href="filecmp.html" />44 45 46 <script defer file-types="bz2,epub,zip" data-domain="docs.python.org" src="https://analytics.python.org/js/script.file-downloads.outbound-links.js"></script>47 48 <link rel="canonical" href="https://docs.python.org/3/library/tempfile.html">49 50 51 52 53 <style>54 @media only screen {55 table.full-width-table {56 width: 100%;57 }58 }59 </style>60<link rel="stylesheet" href="../_static/pydoctheme_dark.css" media="(prefers-color-scheme: dark)" id="pydoctheme_dark_css">61 <link rel="shortcut icon" type="image/png" href="../_static/py.svg">62 <script type="text/javascript" src="../_static/copybutton.js"></script>63 <script type="text/javascript" src="../_static/menu.js"></script>64 <script type="text/javascript" src="../_static/search-focus.js"></script>65 <script type="text/javascript" src="../_static/themetoggle.js"></script> 66 <script type="text/javascript" src="../_static/rtd_switcher.js"></script>67 <meta name="readthedocs-addons-api-version" content="1">68 69 </head>70<body>71<div class="mobile-nav">72 <input type="checkbox" id="menuToggler" class="toggler__input" aria-controls="navigation"73 aria-pressed="false" aria-expanded="false" role="button" aria-label="Menu">74 <nav class="nav-content" role="navigation">75 <label for="menuToggler" class="toggler__label">76 <span></span>77 </label>78 <span class="nav-items-wrapper">79 <a href="https://www.python.org/" class="nav-logo">80 <img src="../_static/py.svg" alt="Python logo">81 </a>82 <span class="version_switcher_placeholder"></span>83 <form role="search" class="search" action="../search.html" method="get">84 <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" class="search-icon">85 <path fill-rule="nonzero" fill="currentColor" d="M15.5 14h-.79l-.28-.27a6.5 6.5 0 001.48-5.34c-.47-2.78-2.79-5-5.59-5.34a6.505 6.505 0 00-7.27 7.27c.34 2.8 2.56 5.12 5.34 5.59a6.5 6.5 0 005.34-1.48l.27.28v.79l4.25 4.25c.41.41 1.08.41 1.49 0 .41-.41.41-1.08 0-1.49L15.5 14zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"></path>86 </svg>87 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q">88 <input type="submit" value="Go">89 </form>90 </span>91 </nav>92 <div class="menu-wrapper">93 <nav class="menu" role="navigation" aria-label="main navigation">94 <div class="language_switcher_placeholder"></div>95 96<label class="theme-selector-label">97 Theme98 <select class="theme-selector" oninput="activateTheme(this.value)">99 <option value="auto" selected>Auto</option>100 <option value="light">Light</option>101 <option value="dark">Dark</option>102 </select>103</label>104 <div>105 <h3><a href="../contents.html">Table of Contents</a></h3>106 <ul>107<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a><ul>108<li><a class="reference internal" href="#examples">Examples</a></li>109<li><a class="reference internal" href="#deprecated-functions-and-variables">Deprecated functions and variables</a></li>110</ul>111</li>112</ul>113 114 </div>115 <div>116 <h4>Previous topic</h4>117 <p class="topless"><a href="filecmp.html"118 title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">filecmp</span></code> — File and Directory Comparisons</a></p>119 </div>120 <div>121 <h4>Next topic</h4>122 <p class="topless"><a href="glob.html"123 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code> — Unix style pathname pattern expansion</a></p>124 </div>125 <script>126 document.addEventListener('DOMContentLoaded', () => {127 const title = document.querySelector('meta[property="og:title"]').content;128 const elements = document.querySelectorAll('.improvepage');129 const pageurl = window.location.href.split('?')[0];130 elements.forEach(element => {131 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));132 url.searchParams.set('pagetitle', title);133 url.searchParams.set('pageurl', pageurl);134 url.searchParams.set('pagesource', "library/tempfile.rst");135 element.href = url.toString();136 });137 });138 </script>139 <div role="note" aria-label="source link">140 <h3>This page</h3>141 <ul class="this-page-menu">142 <li><a href="../bugs.html">Report a bug</a></li>143 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>144 <li>145 <a href="https://github.com/python/cpython/blob/main/Doc/library/tempfile.rst?plain=1"146 rel="nofollow">Show source147 </a>148 </li>149 150 </ul>151 </div>152 </nav>153 </div>154</div>155 156 157 <div class="related" role="navigation" aria-label="Related">158 <h3>Navigation</h3>159 <ul>160 <li class="right" style="margin-right: 10px">161 <a href="../genindex.html" title="General Index"162 accesskey="I">index</a></li>163 <li class="right" >164 <a href="../py-modindex.html" title="Python Module Index"165 >modules</a> |</li>166 <li class="right" >167 <a href="glob.html" title="glob — Unix style pathname pattern expansion"168 accesskey="N">next</a> |</li>169 <li class="right" >170 <a href="filecmp.html" title="filecmp — File and Directory Comparisons"171 accesskey="P">previous</a> |</li>172 173 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>174 <li><a href="https://www.python.org/">Python</a> »</li>175 <li class="switchers">176 <div class="language_switcher_placeholder"></div>177 <div class="version_switcher_placeholder"></div>178 </li>179 <li>180 181 </li>182 <li id="cpython-language-and-version">183 <a href="../index.html">3.15.0a6 Documentation</a> »184 </li>185 186 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>187 <li class="nav-item nav-item-2"><a href="filesys.html" accesskey="U">File and Directory Access</a> »</li>188 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a></li>189 <li class="right">190 191 192 <div class="inline-search" role="search">193 <form class="inline-search" action="../search.html" method="get">194 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">195 <input type="submit" value="Go">196 </form>197 </div>198 |199 </li>200 <li class="right">201<label class="theme-selector-label">202 Theme203 <select class="theme-selector" oninput="activateTheme(this.value)">204 <option value="auto" selected>Auto</option>205 <option value="light">Light</option>206 <option value="dark">Dark</option>207 </select>208</label> |</li>209 210 </ul>211 </div> 212 213 <div class="document">214 <div class="documentwrapper">215 <div class="bodywrapper">216 <div class="body" role="main">217 218 <section id="module-tempfile">219<span id="tempfile-generate-temporary-files-and-directories"></span><h1><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories<a class="headerlink" href="#module-tempfile" title="Link to this heading">¶</a></h1>220<p><strong>Source code:</strong> <a class="extlink-source reference external" href="https://github.com/python/cpython/tree/main/Lib/tempfile.py">Lib/tempfile.py</a></p>221<hr class="docutils" id="index-0" />222<p>This module creates temporary files and directories. It works on all223supported platforms. <a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemporaryFile</span></code></a>, <a class="reference internal" href="#tempfile.NamedTemporaryFile" title="tempfile.NamedTemporaryFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">NamedTemporaryFile</span></code></a>,224<a class="reference internal" href="#tempfile.TemporaryDirectory" title="tempfile.TemporaryDirectory"><code class="xref py py-class docutils literal notranslate"><span class="pre">TemporaryDirectory</span></code></a>, and <a class="reference internal" href="#tempfile.SpooledTemporaryFile" title="tempfile.SpooledTemporaryFile"><code class="xref py py-class docutils literal notranslate"><span class="pre">SpooledTemporaryFile</span></code></a> are high-level225interfaces which provide automatic cleanup and can be used as226<a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context managers</span></a>. <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a> and227<a class="reference internal" href="#tempfile.mkdtemp" title="tempfile.mkdtemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code></a> are lower-level functions which require manual cleanup.</p>228<p>All the user-callable functions and constructors take additional arguments which229allow direct control over the location and name of temporary files and230directories. Files names used by this module include a string of231random characters which allows those files to be securely created in232shared temporary directories.233To maintain backward compatibility, the argument order is somewhat odd; it234is recommended to use keyword arguments for clarity.</p>235<p>The module defines the following user-callable items:</p>236<dl class="py function">237<dt class="sig sig-object py" id="tempfile.TemporaryFile">238<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">TemporaryFile</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'w+b'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffering</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">newline</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">suffix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">prefix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.TemporaryFile" title="Link to this definition">¶</a></dt>239<dd><p>Return a <a class="reference internal" href="../glossary.html#term-file-like-object"><span class="xref std std-term">file-like object</span></a> that can be used as a temporary storage area.240The file is created securely, using the same rules as <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>. It will be destroyed as soon241as it is closed (including an implicit close when the object is garbage242collected). Under Unix, the directory entry for the file is either not created at all or is removed243immediately after the file is created. Other platforms do not support244this; your code should not rely on a temporary file created using this245function having or not having a visible name in the file system.</p>246<p>The resulting object can be used as a <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a> (see247<a class="reference internal" href="#tempfile-examples"><span class="std std-ref">Examples</span></a>). On completion of the context or248destruction of the file object the temporary file will be removed249from the filesystem.</p>250<p>The <em>mode</em> parameter defaults to <code class="docutils literal notranslate"><span class="pre">'w+b'</span></code> so that the file created can251be read and written without being closed. Binary mode is used so that it252behaves consistently on all platforms without regard for the data that is253stored. <em>buffering</em>, <em>encoding</em>, <em>errors</em> and <em>newline</em> are interpreted as for254<a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>.</p>255<p>The <em>dir</em>, <em>prefix</em> and <em>suffix</em> parameters have the same meaning and256defaults as with <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>.</p>257<p>The returned object is a true file object on POSIX platforms. On other258platforms, it is a file-like object whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code> attribute is the259underlying true file object.</p>260<p>The <a class="reference internal" href="os.html#os.O_TMPFILE" title="os.O_TMPFILE"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_TMPFILE</span></code></a> flag is used if it is available and works261(Linux-specific, requires Linux kernel 3.11 or later).</p>262<p>On platforms that are neither Posix nor Cygwin, TemporaryFile is an alias263for NamedTemporaryFile.</p>264<p class="audit-hook">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">tempfile.mkstemp</span></code> with argument <code class="docutils literal notranslate"><span class="pre">fullpath</span></code>.</p>265<div class="versionchanged">266<p><span class="versionmodified changed">Changed in version 3.5: </span>The <a class="reference internal" href="os.html#os.O_TMPFILE" title="os.O_TMPFILE"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_TMPFILE</span></code></a> flag is now used if available.</p>267</div>268<div class="versionchanged">269<p><span class="versionmodified changed">Changed in version 3.8: </span>Added <em>errors</em> parameter.</p>270</div>271</dd></dl>272 273<dl class="py function">274<dt class="sig sig-object py" id="tempfile.NamedTemporaryFile">275<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">NamedTemporaryFile</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'w+b'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffering</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">newline</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">suffix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">prefix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">delete</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">delete_on_close</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.NamedTemporaryFile" title="Link to this definition">¶</a></dt>276<dd><p>This function operates exactly as <a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a> does, except the277following differences:</p>278<ul class="simple">279<li><p>This function returns a file that is guaranteed to have a visible name in280the file system.</p></li>281<li><p>To manage the named file, it extends the parameters of282<a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a> with <em>delete</em> and <em>delete_on_close</em> parameters that283determine whether and how the named file should be automatically deleted.</p></li>284</ul>285<p>The returned object is always a <a class="reference internal" href="../glossary.html#term-file-like-object"><span class="xref std std-term">file-like object</span></a> whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">file</span></code>286attribute is the underlying true file object. This file-like object287can be used in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, just like a normal file. The288name of the temporary file can be retrieved from the <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> attribute289of the returned file-like object. On Unix, unlike with the290<a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a>, the directory entry does not get unlinked immediately291after the file creation.</p>292<p>If <em>delete</em> is true (the default) and <em>delete_on_close</em> is true (the293default), the file is deleted as soon as it is closed. If <em>delete</em> is true294and <em>delete_on_close</em> is false, the file is deleted on context manager exit295only, or else when the <a class="reference internal" href="../glossary.html#term-file-like-object"><span class="xref std std-term">file-like object</span></a> is finalized. Deletion is not296always guaranteed in this case (see <a class="reference internal" href="../reference/datamodel.html#object.__del__" title="object.__del__"><code class="xref py py-meth docutils literal notranslate"><span class="pre">object.__del__()</span></code></a>). If <em>delete</em> is297false, the value of <em>delete_on_close</em> is ignored.</p>298<p>Therefore to use the name of the temporary file to reopen the file after299closing it, either make sure not to delete the file upon closure (set the300<em>delete</em> parameter to be false) or, in case the temporary file is created in301a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, set the <em>delete_on_close</em> parameter to be false.302The latter approach is recommended as it provides assistance in automatic303cleaning of the temporary file upon the context manager exit.</p>304<p>Opening the temporary file again by its name while it is still open works as305follows:</p>306<ul class="simple">307<li><p>On POSIX the file can always be opened again.</p></li>308<li><p>On Windows, make sure that at least one of the following conditions are309fulfilled:</p>310<ul>311<li><p><em>delete</em> is false</p></li>312<li><p>additional open shares delete access (e.g. by calling <a class="reference internal" href="os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>313with the flag <code class="docutils literal notranslate"><span class="pre">O_TEMPORARY</span></code>)</p></li>314<li><p><em>delete</em> is true but <em>delete_on_close</em> is false. Note, that in this315case the additional opens that do not share delete access (e.g.316created via builtin <a class="reference internal" href="functions.html#open" title="open"><code class="xref py py-func docutils literal notranslate"><span class="pre">open()</span></code></a>) must be closed before exiting the317context manager, else the <a class="reference internal" href="os.html#os.unlink" title="os.unlink"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.unlink()</span></code></a> call on context manager318exit will fail with a <a class="reference internal" href="exceptions.html#PermissionError" title="PermissionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PermissionError</span></code></a>.</p></li>319</ul>320</li>321</ul>322<p>On Windows, if <em>delete_on_close</em> is false, and the file is created in a323directory for which the user lacks delete access, then the <a class="reference internal" href="os.html#os.unlink" title="os.unlink"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.unlink()</span></code></a>324call on exit of the context manager will fail with a <a class="reference internal" href="exceptions.html#PermissionError" title="PermissionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PermissionError</span></code></a>.325This cannot happen when <em>delete_on_close</em> is true because delete access is326requested by the open, which fails immediately if the requested access is not327granted.</p>328<p>On POSIX (only), a process that is terminated abruptly with SIGKILL329cannot automatically delete any NamedTemporaryFiles it created.</p>330<p class="audit-hook">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">tempfile.mkstemp</span></code> with argument <code class="docutils literal notranslate"><span class="pre">fullpath</span></code>.</p>331<div class="versionchanged">332<p><span class="versionmodified changed">Changed in version 3.8: </span>Added <em>errors</em> parameter.</p>333</div>334<div class="versionchanged">335<p><span class="versionmodified changed">Changed in version 3.12: </span>Added <em>delete_on_close</em> parameter.</p>336</div>337</dd></dl>338 339<dl class="py class">340<dt class="sig sig-object py" id="tempfile.SpooledTemporaryFile">341<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">SpooledTemporaryFile</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">max_size</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">0</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">mode</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'w+b'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">buffering</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">-1</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">encoding</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">newline</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">suffix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">prefix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.SpooledTemporaryFile" title="Link to this definition">¶</a></dt>342<dd><p>This class operates exactly as <a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a> does, except that343data is spooled in memory until the file size exceeds <em>max_size</em>, or344until the file’s <a class="reference internal" href="io.html#io.IOBase.fileno" title="io.IOBase.fileno"><code class="xref py py-func docutils literal notranslate"><span class="pre">fileno()</span></code></a> method is called, at which point the345contents are written to disk and operation proceeds as with346<code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code>.</p>347<dl class="py method">348<dt class="sig sig-object py" id="tempfile.SpooledTemporaryFile.rollover">349<span class="sig-name descname"><span class="pre">rollover</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.SpooledTemporaryFile.rollover" title="Link to this definition">¶</a></dt>350<dd><p>The resulting file has one additional method, <code class="xref py py-meth docutils literal notranslate"><span class="pre">rollover()</span></code>, which351causes the file to roll over to an on-disk file regardless of its size.</p>352</dd></dl>353 354<p>The returned object is a file-like object whose <code class="xref py py-attr docutils literal notranslate"><span class="pre">_file</span></code> attribute355is either an <a class="reference internal" href="io.html#io.BytesIO" title="io.BytesIO"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.BytesIO</span></code></a> or <a class="reference internal" href="io.html#io.TextIOWrapper" title="io.TextIOWrapper"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.TextIOWrapper</span></code></a> object356(depending on whether binary or text <em>mode</em> was specified) or a true file357object, depending on whether <a class="reference internal" href="#tempfile.SpooledTemporaryFile.rollover" title="tempfile.SpooledTemporaryFile.rollover"><code class="xref py py-meth docutils literal notranslate"><span class="pre">rollover()</span></code></a> has been called. This358file-like object can be used in a <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, just like359a normal file.</p>360<div class="versionchanged">361<p><span class="versionmodified changed">Changed in version 3.3: </span>the truncate method now accepts a <em>size</em> argument.</p>362</div>363<div class="versionchanged">364<p><span class="versionmodified changed">Changed in version 3.8: </span>Added <em>errors</em> parameter.</p>365</div>366<div class="versionchanged">367<p><span class="versionmodified changed">Changed in version 3.11: </span>Fully implements the <a class="reference internal" href="io.html#io.BufferedIOBase" title="io.BufferedIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.BufferedIOBase</span></code></a> and368<a class="reference internal" href="io.html#io.TextIOBase" title="io.TextIOBase"><code class="xref py py-class docutils literal notranslate"><span class="pre">io.TextIOBase</span></code></a> abstract base classes (depending on whether binary369or text <em>mode</em> was specified).</p>370</div>371</dd></dl>372 373<dl class="py class">374<dt class="sig sig-object py" id="tempfile.TemporaryDirectory">375<em class="property"><span class="k"><span class="pre">class</span></span><span class="w"> </span></em><span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">TemporaryDirectory</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">suffix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">prefix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">ignore_cleanup_errors</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em>, <em class="sig-param"><span class="keyword-only-separator o"><abbr title="Keyword-only parameters separator (PEP 3102)"><span class="pre">*</span></abbr></span></em>, <em class="sig-param"><span class="n"><span class="pre">delete</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">True</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.TemporaryDirectory" title="Link to this definition">¶</a></dt>376<dd><p>This class securely creates a temporary directory using the same rules as <a class="reference internal" href="#tempfile.mkdtemp" title="tempfile.mkdtemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code></a>.377The resulting object can be used as a <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a> (see378<a class="reference internal" href="#tempfile-examples"><span class="std std-ref">Examples</span></a>). On completion of the context or destruction379of the temporary directory object, the newly created temporary directory380and all its contents are removed from the filesystem.</p>381<dl class="py attribute">382<dt class="sig sig-object py" id="tempfile.TemporaryDirectory.name">383<span class="sig-name descname"><span class="pre">name</span></span><a class="headerlink" href="#tempfile.TemporaryDirectory.name" title="Link to this definition">¶</a></dt>384<dd><p>The directory name can be retrieved from the <code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> attribute of the385returned object. When the returned object is used as a <a class="reference internal" href="../glossary.html#term-context-manager"><span class="xref std std-term">context manager</span></a>, the386<code class="xref py py-attr docutils literal notranslate"><span class="pre">name</span></code> will be assigned to the target of the <code class="xref std std-keyword docutils literal notranslate"><span class="pre">as</span></code> clause in387the <a class="reference internal" href="../reference/compound_stmts.html#with"><code class="xref std std-keyword docutils literal notranslate"><span class="pre">with</span></code></a> statement, if there is one.</p>388</dd></dl>389 390<dl class="py method">391<dt class="sig sig-object py" id="tempfile.TemporaryDirectory.cleanup">392<span class="sig-name descname"><span class="pre">cleanup</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.TemporaryDirectory.cleanup" title="Link to this definition">¶</a></dt>393<dd><p>The directory can be explicitly cleaned up by calling the394<code class="xref py py-meth docutils literal notranslate"><span class="pre">cleanup()</span></code> method. If <em>ignore_cleanup_errors</em> is true, any unhandled395exceptions during explicit or implicit cleanup (such as a396<a class="reference internal" href="exceptions.html#PermissionError" title="PermissionError"><code class="xref py py-exc docutils literal notranslate"><span class="pre">PermissionError</span></code></a> removing open files on Windows) will be ignored,397and the remaining removable items deleted on a “best-effort” basis.398Otherwise, errors will be raised in whatever context cleanup occurs399(the <code class="xref py py-meth docutils literal notranslate"><span class="pre">cleanup()</span></code> call, exiting the context manager, when the object400is garbage-collected or during interpreter shutdown).</p>401</dd></dl>402 403<p>The <em>delete</em> parameter can be used to disable cleanup of the directory tree404upon exiting the context. While it may seem unusual for a context manager405to disable the action taken when exiting the context, it can be useful during406debugging or when you need your cleanup behavior to be conditional based on407other logic.</p>408<p class="audit-hook">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">tempfile.mkdtemp</span></code> with argument <code class="docutils literal notranslate"><span class="pre">fullpath</span></code>.</p>409<div class="versionadded">410<p><span class="versionmodified added">Added in version 3.2.</span></p>411</div>412<div class="versionchanged">413<p><span class="versionmodified changed">Changed in version 3.10: </span>Added <em>ignore_cleanup_errors</em> parameter.</p>414</div>415<div class="versionchanged">416<p><span class="versionmodified changed">Changed in version 3.12: </span>Added the <em>delete</em> parameter.</p>417</div>418</dd></dl>419 420<dl class="py function">421<dt class="sig sig-object py" id="tempfile.mkstemp">422<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">mkstemp</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">suffix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">prefix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">text</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">False</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.mkstemp" title="Link to this definition">¶</a></dt>423<dd><p>Creates a temporary file in the most secure manner possible. There are424no race conditions in the file’s creation, assuming that the platform425properly implements the <a class="reference internal" href="os.html#os.O_EXCL" title="os.O_EXCL"><code class="xref py py-const docutils literal notranslate"><span class="pre">os.O_EXCL</span></code></a> flag for <a class="reference internal" href="os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>. The426file is readable and writable only by the creating user ID. If the427platform uses permission bits to indicate whether a file is executable,428the file is executable by no one.</p>429<p>The file descriptor is <a class="reference internal" href="os.html#fd-inheritance"><span class="std std-ref">not inherited by child processes</span></a>.</p>430<p>Unlike <a class="reference internal" href="#tempfile.TemporaryFile" title="tempfile.TemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">TemporaryFile()</span></code></a>, the user of <code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code> is responsible431for deleting the temporary file when done with it.</p>432<p>If <em>suffix</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, the file name will end with that suffix,433otherwise there will be no suffix. <code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code> does not put a dot434between the file name and the suffix; if you need one, put it at the435beginning of <em>suffix</em>.</p>436<p>If <em>prefix</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, the file name will begin with that prefix;437otherwise, a default prefix is used. The default is the return value of438<a class="reference internal" href="#tempfile.gettempprefix" title="tempfile.gettempprefix"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettempprefix()</span></code></a> or <a class="reference internal" href="#tempfile.gettempprefixb" title="tempfile.gettempprefixb"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettempprefixb()</span></code></a>, as appropriate.</p>439<p>If <em>dir</em> is not <code class="docutils literal notranslate"><span class="pre">None</span></code>, the file will be created in that directory;440otherwise, a default directory is used. The default directory is chosen441from a platform-dependent list, but the user of the application can442control the directory location by setting the <em>TMPDIR</em>, <em>TEMP</em> or <em>TMP</em>443environment variables. There is thus no guarantee that the generated444filename will have any nice properties, such as not requiring quoting445when passed to external commands via <code class="docutils literal notranslate"><span class="pre">os.popen()</span></code>.</p>446<p>If any of <em>suffix</em>, <em>prefix</em>, and <em>dir</em> are not447<code class="docutils literal notranslate"><span class="pre">None</span></code>, they must be the same type.448If they are bytes, the returned name will be bytes instead of str.449If you want to force a bytes return value with otherwise default behavior,450pass <code class="docutils literal notranslate"><span class="pre">suffix=b''</span></code>.</p>451<p>If <em>text</em> is specified and true, the file is opened in text mode.452Otherwise, (the default) the file is opened in binary mode.</p>453<p><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code> returns a tuple containing an OS-level handle to an open454file (as would be returned by <a class="reference internal" href="os.html#os.open" title="os.open"><code class="xref py py-func docutils literal notranslate"><span class="pre">os.open()</span></code></a>) and the absolute pathname455of that file, in that order.</p>456<p class="audit-hook">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">tempfile.mkstemp</span></code> with argument <code class="docutils literal notranslate"><span class="pre">fullpath</span></code>.</p>457<div class="versionchanged">458<p><span class="versionmodified changed">Changed in version 3.5: </span><em>suffix</em>, <em>prefix</em>, and <em>dir</em> may now be supplied in bytes in order to459obtain a bytes return value. Prior to this, only str was allowed.460<em>suffix</em> and <em>prefix</em> now accept and default to <code class="docutils literal notranslate"><span class="pre">None</span></code> to cause461an appropriate default value to be used.</p>462</div>463<div class="versionchanged">464<p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>dir</em> parameter now accepts a <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p>465</div>466</dd></dl>467 468<dl class="py function">469<dt class="sig sig-object py" id="tempfile.mkdtemp">470<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">mkdtemp</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">suffix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">prefix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.mkdtemp" title="Link to this definition">¶</a></dt>471<dd><p>Creates a temporary directory in the most secure manner possible. There472are no race conditions in the directory’s creation. The directory is473readable, writable, and searchable only by the creating user ID.</p>474<p>The user of <code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code> is responsible for deleting the temporary475directory and its contents when done with it.</p>476<p>The <em>prefix</em>, <em>suffix</em>, and <em>dir</em> arguments are the same as for477<a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>.</p>478<p><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code> returns the absolute pathname of the new directory.</p>479<p class="audit-hook">Raises an <a class="reference internal" href="sys.html#auditing"><span class="std std-ref">auditing event</span></a> <code class="docutils literal notranslate"><span class="pre">tempfile.mkdtemp</span></code> with argument <code class="docutils literal notranslate"><span class="pre">fullpath</span></code>.</p>480<div class="versionchanged">481<p><span class="versionmodified changed">Changed in version 3.5: </span><em>suffix</em>, <em>prefix</em>, and <em>dir</em> may now be supplied in bytes in order to482obtain a bytes return value. Prior to this, only str was allowed.483<em>suffix</em> and <em>prefix</em> now accept and default to <code class="docutils literal notranslate"><span class="pre">None</span></code> to cause484an appropriate default value to be used.</p>485</div>486<div class="versionchanged">487<p><span class="versionmodified changed">Changed in version 3.6: </span>The <em>dir</em> parameter now accepts a <a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p>488</div>489<div class="versionchanged">490<p><span class="versionmodified changed">Changed in version 3.12: </span><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code> now always returns an absolute path, even if <em>dir</em> is relative.</p>491</div>492</dd></dl>493 494<dl class="py function">495<dt class="sig sig-object py" id="tempfile.gettempdir">496<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">gettempdir</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.gettempdir" title="Link to this definition">¶</a></dt>497<dd><p>Return the name of the directory used for temporary files. This498defines the default value for the <em>dir</em> argument to all functions499in this module.</p>500<p>Python searches a standard list of directories to find one which501the calling user can create files in. The list is:</p>502<ol class="arabic simple">503<li><p>The directory named by the <span class="target" id="index-1"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TMPDIR</span></code> environment variable.</p></li>504<li><p>The directory named by the <span class="target" id="index-2"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TEMP</span></code> environment variable.</p></li>505<li><p>The directory named by the <span class="target" id="index-3"></span><code class="xref std std-envvar docutils literal notranslate"><span class="pre">TMP</span></code> environment variable.</p></li>506<li><p>A platform-specific location:</p>507<ul class="simple">508<li><p>On Windows, the directories <code class="file docutils literal notranslate"><span class="pre">C:\TEMP</span></code>, <code class="file docutils literal notranslate"><span class="pre">C:\TMP</span></code>,509<code class="file docutils literal notranslate"><span class="pre">\TEMP</span></code>, and <code class="file docutils literal notranslate"><span class="pre">\TMP</span></code>, in that order.</p></li>510<li><p>On all other platforms, the directories <code class="file docutils literal notranslate"><span class="pre">/tmp</span></code>, <code class="file docutils literal notranslate"><span class="pre">/var/tmp</span></code>, and511<code class="file docutils literal notranslate"><span class="pre">/usr/tmp</span></code>, in that order.</p></li>512</ul>513</li>514<li><p>As a last resort, the current working directory.</p></li>515</ol>516<p>The result of this search is cached, see the description of517<a class="reference internal" href="#tempfile.tempdir" title="tempfile.tempdir"><code class="xref py py-data docutils literal notranslate"><span class="pre">tempdir</span></code></a> below.</p>518<div class="versionchanged">519<p><span class="versionmodified changed">Changed in version 3.10: </span>Always returns a str. Previously it would return any <a class="reference internal" href="#tempfile.tempdir" title="tempfile.tempdir"><code class="xref py py-data docutils literal notranslate"><span class="pre">tempdir</span></code></a>520value regardless of type so long as it was not <code class="docutils literal notranslate"><span class="pre">None</span></code>.</p>521</div>522</dd></dl>523 524<dl class="py function">525<dt class="sig sig-object py" id="tempfile.gettempdirb">526<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">gettempdirb</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.gettempdirb" title="Link to this definition">¶</a></dt>527<dd><p>Same as <a class="reference internal" href="#tempfile.gettempdir" title="tempfile.gettempdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettempdir()</span></code></a> but the return value is in bytes.</p>528<div class="versionadded">529<p><span class="versionmodified added">Added in version 3.5.</span></p>530</div>531</dd></dl>532 533<dl class="py function">534<dt class="sig sig-object py" id="tempfile.gettempprefix">535<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">gettempprefix</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.gettempprefix" title="Link to this definition">¶</a></dt>536<dd><p>Return the filename prefix used to create temporary files. This does not537contain the directory component.</p>538</dd></dl>539 540<dl class="py function">541<dt class="sig sig-object py" id="tempfile.gettempprefixb">542<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">gettempprefixb</span></span><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.gettempprefixb" title="Link to this definition">¶</a></dt>543<dd><p>Same as <a class="reference internal" href="#tempfile.gettempprefix" title="tempfile.gettempprefix"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettempprefix()</span></code></a> but the return value is in bytes.</p>544<div class="versionadded">545<p><span class="versionmodified added">Added in version 3.5.</span></p>546</div>547</dd></dl>548 549<p>The module uses a global variable to store the name of the directory550used for temporary files returned by <a class="reference internal" href="#tempfile.gettempdir" title="tempfile.gettempdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettempdir()</span></code></a>. It can be551set directly to override the selection process, but this is discouraged.552All functions in this module take a <em>dir</em> argument which can be used553to specify the directory. This is the recommended approach that does554not surprise other unsuspecting code by changing global API behavior.</p>555<dl class="py data">556<dt class="sig sig-object py" id="tempfile.tempdir">557<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">tempdir</span></span><a class="headerlink" href="#tempfile.tempdir" title="Link to this definition">¶</a></dt>558<dd><p>When set to a value other than <code class="docutils literal notranslate"><span class="pre">None</span></code>, this variable defines the559default value for the <em>dir</em> argument to the functions defined in this560module, including its type, bytes or str. It cannot be a561<a class="reference internal" href="../glossary.html#term-path-like-object"><span class="xref std std-term">path-like object</span></a>.</p>562<p>If <code class="docutils literal notranslate"><span class="pre">tempdir</span></code> is <code class="docutils literal notranslate"><span class="pre">None</span></code> (the default) at any call to any of the above563functions except <a class="reference internal" href="#tempfile.gettempprefix" title="tempfile.gettempprefix"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettempprefix()</span></code></a> it is initialized following the564algorithm described in <a class="reference internal" href="#tempfile.gettempdir" title="tempfile.gettempdir"><code class="xref py py-func docutils literal notranslate"><span class="pre">gettempdir()</span></code></a>.</p>565<div class="admonition note">566<p class="admonition-title">Note</p>567<p>Beware that if you set <code class="docutils literal notranslate"><span class="pre">tempdir</span></code> to a bytes value, there is a568nasty side effect: The global default return type of569<a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a> and <a class="reference internal" href="#tempfile.mkdtemp" title="tempfile.mkdtemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkdtemp()</span></code></a> changes to bytes when no570explicit <code class="docutils literal notranslate"><span class="pre">prefix</span></code>, <code class="docutils literal notranslate"><span class="pre">suffix</span></code>, or <code class="docutils literal notranslate"><span class="pre">dir</span></code> arguments of type571str are supplied. Please do not write code expecting or572depending on this. This awkward behavior is maintained for573compatibility with the historical implementation.</p>574</div>575</dd></dl>576 577<section id="examples">578<span id="tempfile-examples"></span><h2>Examples<a class="headerlink" href="#examples" title="Link to this heading">¶</a></h2>579<p>Here are some examples of typical usage of the <code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code> module:</p>580<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="kn">import</span><span class="w"> </span><span class="nn">tempfile</span>581 582<span class="go"># create a temporary file and write some data to it</span>583<span class="gp">>>> </span><span class="n">fp</span> <span class="o">=</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">TemporaryFile</span><span class="p">()</span>584<span class="gp">>>> </span><span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s1">'Hello world!'</span><span class="p">)</span>585<span class="go"># read data from file</span>586<span class="gp">>>> </span><span class="n">fp</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>587<span class="gp">>>> </span><span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>588<span class="go">b'Hello world!'</span>589<span class="go"># close the file, it will be removed</span>590<span class="gp">>>> </span><span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>591 592<span class="go"># create a temporary file using a context manager</span>593<span class="gp">>>> </span><span class="k">with</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">TemporaryFile</span><span class="p">()</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>594<span class="gp">... </span> <span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s1">'Hello world!'</span><span class="p">)</span>595<span class="gp">... </span> <span class="n">fp</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>596<span class="gp">... </span> <span class="n">fp</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>597<span class="go">b'Hello world!'</span>598<span class="gp">>>></span>599<span class="go"># file is now closed and removed</span>600 601<span class="go"># create a temporary file using a context manager</span>602<span class="go"># close the file, use the name to open the file again</span>603<span class="gp">>>> </span><span class="k">with</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">NamedTemporaryFile</span><span class="p">(</span><span class="n">delete_on_close</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span> <span class="k">as</span> <span class="n">fp</span><span class="p">:</span>604<span class="gp">... </span> <span class="n">fp</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s1">'Hello world!'</span><span class="p">)</span>605<span class="gp">... </span> <span class="n">fp</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>606<span class="gp">... </span><span class="c1"># the file is closed, but not removed</span>607<span class="gp">... </span><span class="c1"># open the file again by using its name</span>608<span class="gp">... </span> <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">fp</span><span class="o">.</span><span class="n">name</span><span class="p">,</span> <span class="n">mode</span><span class="o">=</span><span class="s1">'rb'</span><span class="p">)</span> <span class="k">as</span> <span class="n">f</span><span class="p">:</span>609<span class="gp">... </span> <span class="n">f</span><span class="o">.</span><span class="n">read</span><span class="p">()</span>610<span class="go">b'Hello world!'</span>611<span class="gp">>>></span>612<span class="go"># file is now removed</span>613 614<span class="go"># create a temporary directory using the context manager</span>615<span class="gp">>>> </span><span class="k">with</span> <span class="n">tempfile</span><span class="o">.</span><span class="n">TemporaryDirectory</span><span class="p">()</span> <span class="k">as</span> <span class="n">tmpdirname</span><span class="p">:</span>616<span class="gp">... </span> <span class="nb">print</span><span class="p">(</span><span class="s1">'created temporary directory'</span><span class="p">,</span> <span class="n">tmpdirname</span><span class="p">)</span>617<span class="gp">>>></span>618<span class="go"># directory and contents have been removed</span>619</pre></div>620</div>621</section>622<section id="deprecated-functions-and-variables">623<span id="tempfile-mktemp-deprecated"></span><h2>Deprecated functions and variables<a class="headerlink" href="#deprecated-functions-and-variables" title="Link to this heading">¶</a></h2>624<p>A historical way to create temporary files was to first generate a625file name with the <a class="reference internal" href="#tempfile.mktemp" title="tempfile.mktemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mktemp()</span></code></a> function and then create a file626using this name. Unfortunately this is not secure, because a different627process may create a file with this name in the time between the call628to <code class="xref py py-func docutils literal notranslate"><span class="pre">mktemp()</span></code> and the subsequent attempt to create the file by the629first process. The solution is to combine the two steps and create the630file immediately. This approach is used by <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a> and the631other functions described above.</p>632<dl class="py function">633<dt class="sig sig-object py" id="tempfile.mktemp">634<span class="sig-prename descclassname"><span class="pre">tempfile.</span></span><span class="sig-name descname"><span class="pre">mktemp</span></span><span class="sig-paren">(</span><em class="sig-param"><span class="n"><span class="pre">suffix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">''</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">prefix</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">'tmp'</span></span></em>, <em class="sig-param"><span class="n"><span class="pre">dir</span></span><span class="o"><span class="pre">=</span></span><span class="default_value"><span class="pre">None</span></span></em><span class="sig-paren">)</span><a class="headerlink" href="#tempfile.mktemp" title="Link to this definition">¶</a></dt>635<dd><div class="deprecated">636<p><span class="versionmodified deprecated">Deprecated since version 2.3: </span>Use <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a> instead.</p>637</div>638<p>Return an absolute pathname of a file that did not exist at the time the639call is made. The <em>prefix</em>, <em>suffix</em>, and <em>dir</em> arguments are similar640to those of <a class="reference internal" href="#tempfile.mkstemp" title="tempfile.mkstemp"><code class="xref py py-func docutils literal notranslate"><span class="pre">mkstemp()</span></code></a>, except that bytes file names, <code class="docutils literal notranslate"><span class="pre">suffix=None</span></code>641and <code class="docutils literal notranslate"><span class="pre">prefix=None</span></code> are not supported.</p>642<div class="admonition warning">643<p class="admonition-title">Warning</p>644<p>Use of this function may introduce a security hole in your program. By645the time you get around to doing anything with the file name it returns,646someone else may have beaten you to the punch. <code class="xref py py-func docutils literal notranslate"><span class="pre">mktemp()</span></code> usage can647be replaced easily with <a class="reference internal" href="#tempfile.NamedTemporaryFile" title="tempfile.NamedTemporaryFile"><code class="xref py py-func docutils literal notranslate"><span class="pre">NamedTemporaryFile()</span></code></a>, passing it the648<code class="docutils literal notranslate"><span class="pre">delete=False</span></code> parameter:</p>649<div class="highlight-python3 notranslate"><div class="highlight"><pre><span></span><span class="gp">>>> </span><span class="n">f</span> <span class="o">=</span> <span class="n">NamedTemporaryFile</span><span class="p">(</span><span class="n">delete</span><span class="o">=</span><span class="kc">False</span><span class="p">)</span>650<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">name</span>651<span class="go">'/tmp/tmptjujjt'</span>652<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="sa">b</span><span class="s2">"Hello World!</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span>653<span class="go">13</span>654<span class="gp">>>> </span><span class="n">f</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>655<span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">unlink</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>656<span class="gp">>>> </span><span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">f</span><span class="o">.</span><span class="n">name</span><span class="p">)</span>657<span class="go">False</span>658</pre></div>659</div>660</div>661</dd></dl>662 663</section>664</section>665 666 667 <div class="clearer"></div>668 </div>669 </div>670 </div>671 <div class="sphinxsidebar" role="navigation" aria-label="Main">672 <div class="sphinxsidebarwrapper">673 <div>674 <h3><a href="../contents.html">Table of Contents</a></h3>675 <ul>676<li><a class="reference internal" href="#"><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a><ul>677<li><a class="reference internal" href="#examples">Examples</a></li>678<li><a class="reference internal" href="#deprecated-functions-and-variables">Deprecated functions and variables</a></li>679</ul>680</li>681</ul>682 683 </div>684 <div>685 <h4>Previous topic</h4>686 <p class="topless"><a href="filecmp.html"687 title="previous chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">filecmp</span></code> — File and Directory Comparisons</a></p>688 </div>689 <div>690 <h4>Next topic</h4>691 <p class="topless"><a href="glob.html"692 title="next chapter"><code class="xref py py-mod docutils literal notranslate"><span class="pre">glob</span></code> — Unix style pathname pattern expansion</a></p>693 </div>694 <script>695 document.addEventListener('DOMContentLoaded', () => {696 const title = document.querySelector('meta[property="og:title"]').content;697 const elements = document.querySelectorAll('.improvepage');698 const pageurl = window.location.href.split('?')[0];699 elements.forEach(element => {700 const url = new URL(element.href.split('?')[0].replace("-nojs", ""));701 url.searchParams.set('pagetitle', title);702 url.searchParams.set('pageurl', pageurl);703 url.searchParams.set('pagesource', "library/tempfile.rst");704 element.href = url.toString();705 });706 });707 </script>708 <div role="note" aria-label="source link">709 <h3>This page</h3>710 <ul class="this-page-menu">711 <li><a href="../bugs.html">Report a bug</a></li>712 <li><a class="improvepage" href="../improve-page-nojs.html">Improve this page</a></li>713 <li>714 <a href="https://github.com/python/cpython/blob/main/Doc/library/tempfile.rst?plain=1"715 rel="nofollow">Show source716 </a>717 </li>718 719 </ul>720 </div>721 </div>722<div id="sidebarbutton" title="Collapse sidebar">723<span>«</span>724</div>725 726 </div>727 <div class="clearer"></div>728 </div> 729 <div class="related" role="navigation" aria-label="Related">730 <h3>Navigation</h3>731 <ul>732 <li class="right" style="margin-right: 10px">733 <a href="../genindex.html" title="General Index"734 >index</a></li>735 <li class="right" >736 <a href="../py-modindex.html" title="Python Module Index"737 >modules</a> |</li>738 <li class="right" >739 <a href="glob.html" title="glob — Unix style pathname pattern expansion"740 >next</a> |</li>741 <li class="right" >742 <a href="filecmp.html" title="filecmp — File and Directory Comparisons"743 >previous</a> |</li>744 745 <li><img src="../_static/py.svg" alt="Python logo" style="vertical-align: middle; margin-top: -1px"></li>746 <li><a href="https://www.python.org/">Python</a> »</li>747 <li class="switchers">748 <div class="language_switcher_placeholder"></div>749 <div class="version_switcher_placeholder"></div>750 </li>751 <li>752 753 </li>754 <li id="cpython-language-and-version">755 <a href="../index.html">3.15.0a6 Documentation</a> »756 </li>757 758 <li class="nav-item nav-item-1"><a href="index.html" >The Python Standard Library</a> »</li>759 <li class="nav-item nav-item-2"><a href="filesys.html" >File and Directory Access</a> »</li>760 <li class="nav-item nav-item-this"><a href=""><code class="xref py py-mod docutils literal notranslate"><span class="pre">tempfile</span></code> — Generate temporary files and directories</a></li>761 <li class="right">762 763 764 <div class="inline-search" role="search">765 <form class="inline-search" action="../search.html" method="get">766 <input placeholder="Quick search" aria-label="Quick search" type="search" name="q" id="search-box">767 <input type="submit" value="Go">768 </form>769 </div>770 |771 </li>772 <li class="right">773<label class="theme-selector-label">774 Theme775 <select class="theme-selector" oninput="activateTheme(this.value)">776 <option value="auto" selected>Auto</option>777 <option value="light">Light</option>778 <option value="dark">Dark</option>779 </select>780</label> |</li>781 782 </ul>783 </div> 784 <div class="footer">785 © <a href="../copyright.html">Copyright</a> 2001 Python Software Foundation.786 <br>787 This page is licensed under the Python Software Foundation License Version 2.788 <br>789 Examples, recipes, and other code in the documentation are additionally licensed under the Zero Clause BSD License.790 <br>791 792 See <a href="/license.html">History and License</a> for more information.<br>793 794 795 <br>796 797 The Python Software Foundation is a non-profit corporation.798<a href="https://www.python.org/psf/donations/">Please donate.</a>799<br>800 <br>801 Last updated on Mar 10, 2026 (08:58 UTC).802 803 <a href="/bugs.html">Found a bug</a>?804 805 <br>806 807 Created using <a href="https://www.sphinx-doc.org/">Sphinx</a> 8.2.3.808 </div>809 810 </body>811</html>