avatarOliver S

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

1724

Abstract

4f">context manager</a>.</p><p id="0c81">Let’s look at one example, one time using an explicit close, and one time using a context manager.</p><h2 id="0971">TemporaryFile() with Explicit Close</h2><div id="15a0"><pre>temp_file = tempfile.TemporaryFile(<span class="hljs-string">"w+"</span>) temp_file.write(<span class="hljs-string">"Temp content"</span>) temp_file.seek(<span class="hljs-number">0</span>) <span class="hljs-comment"># Jump back to beginning of file, otherwise read will be empty.</span> <span class="hljs-built_in">print</span>(temp_file.read()) temp_file.close()</pre></div><h2 id="eb39">TemporaryFile() with Context Manager</h2><div id="f337"><pre><span class="hljs-keyword">import</span> tempfile

<span class="hljs-keyword">with</span> tempfile.TemporaryFile(<span class="hljs-string">"w+"</span>) <span class="hljs-keyword">as</span> temp_file: temp_file.write(<span class="hljs-string">"Temp content"</span>) temp_file.seek(<span class="hljs-number">0</span>) <span class="hljs-comment"># Jump back to beginning of file, otherwise read will be empty.</span> <span class="hljs-built_in">print</span>(temp_file.read())</pre></div><p id="3af9">Note that also lower-level functions are available, such as <code>mkstemp()</code> and <code>mkdtemp()</code>, which also generate temporary files / directories, but require manual clean-up — i.e. if not needed for some reason, stick to the higher-level calls as described above.</p><p id="5c45">Thanks for reading!</p><p id="90bf">This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:</p><ul><li>Part 1: <a href="https://readmedium.com/lambda-functions-in-python-a124cebc2e99">Lambda Funct

Options

ions in Python</a></li><li>Part 2: <a href="https://readmedium.com/iterators-in-python-bd7332ddbc00">Iterators in Python</a></li><li>Part 3: <a href="https://readmedium.com/generators-and-generator-expressions-in-python-a8d2e700945e">Generators and Generator Expressions in Python</a></li><li>Part 4: <a href="https://readmedium.com/advanced-iteration-in-python-with-enumerate-and-zip-676b31ceac44">Advanced Iteration in Python with enumerate() and zip()</a></li><li>Part 5: <a href="https://readmedium.com/managing-resources-in-python-with-context-managers-with-statement-f07afc1afb4f">Managing Resources in Python with Context Managers (with statement)</a></li><li>Part 7: <a href="https://readmedium.com/logging-in-python-3df84ce78cef">Logging in Python</a></li><li>Part 8: <a href="https://readmedium.com/partial-functions-in-python-66998eef1384">Partial Functions in Python</a></li><li>Part 9: <a href="https://readmedium.com/f-strings-in-python-80e30c64fb95">f-Strings in Python</a></li></ul><p id="6e13"><i>More content at <a href="https://plainenglish.io/"><b>PlainEnglish.io</b></a>. Sign up for our <a href="http://newsletter.plainenglish.io/"><b>free weekly newsletter</b></a>. Join our <a href="https://discord.gg/GtDtUAvyhW"><b>Discord</b></a> community and follow us on <a href="https://twitter.com/inPlainEngHQ"><b>Twitter</b></a></i>, <a href="https://www.linkedin.com/company/inplainenglish/"><b><i>LinkedIn</i></b></a><i> and<b> <a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw">YouTube</a>.</b></i></p><p id="8c0e"><b><i>Learn how to build awareness and adoption for your startup with <a href="https://circuit.ooo/?utm=publication-post-cta">Circuit</a></i></b><i>.</i></p></article></body>

Generating Temporary Files and Directories in Python

Python Shorts — Part 6

Photo by Chris Ried on Unsplash

Developers often need some temporary files or folders, e.g. for unit tests, or just to store any kind of temporary information. For this purpose, they don’t care where these files are placed, how they are named, etc.

One way of achieving this would be create some file / directory manually, e.g. in /tmp, using it, and eventually deleting it manually. This works, but is clunky, you might need to check if the file already exists by coincidence, etc.

Fortunately for us, Python offers some convenience functions in the form of the tempfile module. This e.g. offers the functions TemporaryFile() and TemporaryDirectory(), creating a temporary file / directory, respectively. This is done in a “safe” manner, i.e. uninterrupted, the call makes sure a name is chosen which does not exist yet, places it somewhere “hard-to-find” — and eventually deletes the file / folder when done. This deletion for files is done when the file is closed either explicitly or using a context manager.

Let’s look at one example, one time using an explicit close, and one time using a context manager.

TemporaryFile() with Explicit Close

temp_file = tempfile.TemporaryFile("w+")
temp_file.write("Temp content")
temp_file.seek(0) # Jump back to beginning of file, otherwise read will be empty.
print(temp_file.read())
temp_file.close()

TemporaryFile() with Context Manager

import tempfile

with tempfile.TemporaryFile("w+") as temp_file:
    temp_file.write("Temp content")
    temp_file.seek(0) # Jump back to beginning of file, otherwise read will be empty.
    print(temp_file.read())

Note that also lower-level functions are available, such as mkstemp() and mkdtemp(), which also generate temporary files / directories, but require manual clean-up — i.e. if not needed for some reason, stick to the higher-level calls as described above.

Thanks for reading!

This post is part of a series show-casing important Python concepts quickly. You can find the other parts here:

More content at PlainEnglish.io. Sign up for our free weekly newsletter. Join our Discord community and follow us on Twitter, LinkedIn and YouTube.

Learn how to build awareness and adoption for your startup with Circuit.

Python
Python Programming
Python3
Recommended from ReadMedium