Let's study Python

Create temporary files and directories in Python with the `tempfile` module for easy and temporary storage.

# Python Tempfile Module

In Python programming, the `tempfile` module provides functionality to create temporary files and directories. This post explores how to create temporary files or directories using the `tempfile` module.

## Temporary File Creation

When creating temporary files, the `TemporaryFile()` function of the `tempfile` module is used. Let’s look at an example of creating a simple temporary file and writing/reading text mode.

“`python
from tempfile import TemporaryFile

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

The first argument of the `TemporaryFile()` function specifies the file mode. `”w+t”` indicates text mode, while `”w+b”` indicates binary mode. Both modes support reading and writing simultaneously. When the temporary file is closed, it is removed.

Using a context manager, the above code can be modified as follows:

“`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 filename, you can use the `NamedTemporaryFile()` function:

“`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)
“`

## Temporary Directory Creation

The `TemporaryDirectory()` function of the `tempfile` module is used to create temporary directories. It is similar to using `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 they are closed.

## Summary

– The `TemporaryFile()` and `NamedTemporaryFile()` functions of the `tempfile` module can be used to create temporary files.
– Temporary file modes include text mode `’w+t’` and binary mode `’b+t’`.
– The `TemporaryDirectory()` function of the `tempfile` module allows the creation of temporary directories.
– Temporary files and directories are automatically removed when closed.

## References

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