Let's study Python

Creating temporary files and directories in Python using the `tempfile` module is simple and convenient, allowing for easy management of temporary data.

## Python `tempfile` Module

### Introduction
This post explores how to create temporary files or directories using Python’s `tempfile` module.

### Python Version
Python 3.9.6

### Creating Temporary Files
When creating temporary files, we use the `TemporaryFile()` function from the `tempfile` module. Let’s look at an example of creating a simple temporary file and writing/reading text to/from it:

“`python
from tempfile import TemporaryFile

fp = TemporaryFile(“w+t”)
fp.write(“Hello”)
fp.seek(0)
data = fp.read()
print(data)
fp.close()
“`

In the code snippet above, the first argument of the `TemporaryFile()` function is the file mode. `”w+t”` indicates text mode, while `”w+b”` would indicate binary mode. These modes support both reading and writing simultaneously. When the temporary file is closed, it is removed.

The `TemporaryFile()` function can also be used with a context manager as shown below:

“`python
from tempfile import TemporaryFile

with TemporaryFile(“w+t”) as fp:
fp.write(“Hello”)
fp.seek(0)
data = fp.read()
print(data)
“`

On Windows systems, temporary files are typically stored in `”C:\Users\username\…\Temp”`, while on Unix systems, they are stored in `”/tmp”`, `”/var/tmp”`, or `”/usr/tmp”`.

For Unix systems, if you want to specify an arbitrary file name, you can use the `NamedTemporaryFile()` function from the `tempfile` module:

“`python
from tempfile import NamedTemporaryFile

with NamedTemporaryFile(“w+t”) as fp:
fp.write(“Hello”)
print(“File name:”, fp.name)
fp.seek(0)
data = fp.read()
print(data)
“`

### Creating Temporary Directories
The `TemporaryDirectory()` function from the `tempfile` module is used to create temporary directories. Its usage is similar to that of `TemporaryFile()`.

“`python
import os
from tempfile import TemporaryDirectory

with TemporaryDirectory() as tmpdir:
print(“Temporary directory created:”, tmpdir)
print(os.path.exists(tmpdir))
# Temporary directory is automatically removed
print(os.path.exists(tmpdir))
“`

Temporary files and directories are automatically removed when closed.

### Summary
– Temporary files can be created using `TemporaryFile()` and `NamedTemporaryFile()` functions.
– Temporary file modes include text mode `’w+t’` and binary mode `’b+t’`.
– Temporary directories can be created using the `TemporaryDirectory()` function.
– Temporary files and directories are automatically removed when closed.

### References
1. Python Cookbook, Infinity Books, pp. 167-169
2. [Naver Blog – Python tempfile](https://m.blog.naver.com/hankrah/221831304924)