# Python Tempfile Module

The `tempfile` module generates temporary files and directories. It works on all supported platforms.

## Importing the Module

```python
import tempfile
```

## Temporary Files

### `TemporaryFile`

Creates a temporary file. The file is created using `mkstemp()`. It is destroyed as soon as it is closed (including an implicit close when the object is garbage collected).

**Note:** Under Unix, the directory entry for the file is either not created at all or is removed immediately after the file is created. This means the file is not visible in the file system.

```python
import tempfile

# Create a temporary file and write some data to it
fp = tempfile.TemporaryFile()
fp.write(b'Hello world!')
fp.seek(0)
print(fp.read()) # Output: b'Hello world!'
fp.close()
```

### `NamedTemporaryFile`

This function operates exactly as `TemporaryFile()`, except that the file is guaranteed to have a visible name in the file system (on Unix, the directory entry is not unlinked). That name can be retrieved from the `name` attribute of the returned file-like object.

```python
import tempfile
import os

# delete=False prevents automatic deletion on close
f = tempfile.NamedTemporaryFile(delete=False)
print(f.name) # Output: /tmp/tmp... (path to temp file)
f.write(b'Hello World')
f.close()

# Clean up manually if delete=False
os.unlink(f.name)
```

## Temporary Directories

### `TemporaryDirectory`

Creates a temporary directory. On completion of the context or destruction of the temporary directory object, the newly created temporary directory and all its contents are removed from the filesystem.

```python
import tempfile
import os

with tempfile.TemporaryDirectory() as tmpdirname:
    print('Created temporary directory:', tmpdirname)
    # Do something with the directory...
    filepath = os.path.join(tmpdirname, 'test.txt')
    with open(filepath, 'w') as f:
        f.write('hello')

# Directory and contents are removed here
```

## Utility Functions

### `gettempdir()`

Return the name of the directory used for temporary files.

```python
import tempfile

print(tempfile.gettempdir())
```

[[programming/python/python]]