Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Creating Temporary Files and Directories

00:00 In this lesson, I’ll show you how to work with temporary files and directories, which can be really valuable tools—especially for testing—because there might be situations where you want to write functions or classes or whatever, that operate on files and directories, but you want to be able to test them without risking corrupting your filesystem.

00:18 So these can be super useful in that context, as well as in many others.

00:23 As you might guess, the functions from the tempfile module that’ll be demonstrating are tempfile.TemporaryFile() which takes in a file mode and creates and opens a temporary file in that mode.

00:35 And then tempfile.TemporaryDirectory(), and that creates a temporary directory and just returns it for your use. So, very simple. I won’t really be using a sample directory for this because, of course, I’ll be creating and then deleting immediately all of the temporary files and directories that I use for this lesson. As usual, you need to get your imports going, which in this case is just tempfile, but I’m also going to import os so that I can just show you that I’m in an empty directory.

01:03 And then, if you don’t want to mess with this directory, you’ll need to use some temporary files. So, since tempfile supports the context manager protocol, it’s very easy to do that by saying with tempfile.TemporaryFile(), and then I’m going to pass in the mode just 'w+', which means read and write, as opposed to 'w+b', which means read and write bytes, because I want to just read and write strings.

01:28 And I’m not going to use the other parameters of this. There are a lot of other parameters, but check those out on your own time if you’d like to. For this demonstration, they won’t be super important.

01:37 So, with tempfile.TemporaryFile('w+'), in read and write mode, as temp, I can just say temp.writejust as I would with any other file—"I'm a temp file!" And then, I’m actually going to use the .seek() function to go all the way back to the beginning of the file so that I can then print out all the contents of the file.

01:58 I’ll say, print(, and as you can see, it correctly reads, I'm a temp file! But if I try to say here, it’ll say I/O operation on a closed file. And in fact, it’s not only a closed file, it’s also a nonexistent file because temp is now just an IO wrapper that points to an empty file.

02:18 Similar things tend to happen when you use tempfile.TemporaryDirectory(), except the temporary directory—again, I won’t really use all the parameters here, I’ll just use a base directory—except the temporary directory is, in fact, just a string.

02:32 So I can print out temp_dir, it’s just the path of this new directory, and then I’ll use os.path.exists() to make sure that it does, in fact,

02:43 exist, according to the filesystem. And as you can see, that’s True, and it’s in this kind of weird directory, and this will totally vary by your system.

02:51 My system is putting this in a strange directory. Most of the time it will be in, like, /tmp (temp), or something like that, but for me, it’s in this kind of odd directory, just cause of quirks in how my system works.

03:03 But you can also—in here, you have all the options available to you that you normally do, inside this object. For example, you could start opening files in here.

03:12 You could start doing whatever you wanted to do, just as you normally would with a directory. But now, of course, when I say os.path.exists() outside of this with block, that will give me False, because at the end of this context managed block, the resources are all deleted and they have no lasting effect on your filesystem.

03:31 So that’s tremendously convenient and important in both of these patterns because it means that you can essentially do whatever you want with these files or directories, and none of it will have any lasting effect on your system, beyond the end of this with as block.

03:45 So that’s why temp files and temporary directories are important and useful: because there are a lot of cases where you might want to do things with files or test things with files, but you don’t actually want to risk, say, deleting a really important file somewhere in your filesystem.

03:59 In the next lesson, I’ll cover how to copy, move, and rename files and directories.

tonypy on March 15, 2023

Just an observation running the suggested content on Windows.

With the ‘w+’ mode, the output is:

I'm a temp file!

The same result for ‘r+’ and ‘a+’.

For interest I ran through all the other possible modes:

io.UnsupportedOperation: not writable > r 
io.UnsupportedOperation: write > rb 
TypeError: a bytes-like object is required, not 'str' > r+b, rb+, wb, w+b, wb+, ab, a+b, ab+
io.UnsupportedOperation: not readable > w, a, x

Any suggestions as to why ‘w+’ provides the number of characters written to the file (16) plus the seek offset (0) and then the text entry?

Become a Member to join the conversation.