In this video, learn how to use the tempfile module to create, write, and read temporary files. These files can be set to erase once closed, or at program termination.
- [Instructor] We can use the tempfile module to create temporary files in Python, but in order to use the tempfile module, we have to import it. And so, to import it, we'll go, import tempfile. Now that we have access to it, we'll go ahead and create a temporary file. To do this, we'll create a variable, so, tempFile, which will hold our temporary file that we create. And then, to create the temporary file, we'll access the module, so, tempfile., and then the TemporaryFile constructor there, and that will create our temporary file.
Now that our temporary file is stored inside of tempfile, we'll go ahead and access tempFile, and this is how we're going to write to the file. And so, we'll go write, and what we're going to want to write to this temporary file is just a special number, and so we'll say, Save this special number for me. It'll be 5678, and then, 309. And this is your special number that you're saving. However, we're not done yet, and that's because this write method takes a bytes object.
And here, we have a string. In order to turn this string into a bytes object, we add b here, and that actually turns it into a bytes literal. And now that we've written something to the file, we'll need to go ahead and reset the seek pointer for the file, and so we'll go tempFile.seek, set that pointer back to zero, so then we can read from this temporary file. And so, to read from it, we'll just go print tempFile.read, and this will print everything we read from the file, which is what we just wrote to the file.
And then, once we're done with the file, we'll go ahead and close it with tempFile.close. And so, it's pretty similar to how we worked with files in previous videos. Running this, we see, Save this special number for me, and it has the special number. So with temporary files, we created a file, wrote to it, moved the seek pointer, and then read it and printed it out to the output in the console. So if you have a program where you need to store some data easily just for the program's execution, this might be the module for you.
- Working with logical and comparison operators
- Getting a list of numbers with the range() and list() functions
- Using mathematical functions such as round(), abs(), and pow()
- Calculating a given input's length
- Importing and using the math module
- Reading a user's command-line arguments
- Getting the current time
- Formatting dates and times with datetime
- Creating a timer
- Using urllib to get content from the Internet
- Using the JSON module to decode content