# Python Shutil Module

The `shutil` module offers a number of high-level operations on files and collections of files. In particular, functions are provided which support file copying and removal.

## Importing the Module

```python
import shutil
```

## Copying Files

### `shutil.copy()`

Copies the file `src` to the file or directory `dst`. Permissions are copied, but metadata like creation time might not be.

```python
import shutil

shutil.copy('source.txt', 'destination.txt')
```

### `shutil.copy2()`

Identical to `copy()`, but attempts to preserve file metadata (timestamps, etc.).

```python
shutil.copy2('source.txt', 'destination.txt')
```

## Copying Directories

### `shutil.copytree()`

Recursively copies an entire directory tree rooted at `src` to a directory named `dst`. The destination directory must not already exist.

```python
import shutil

shutil.copytree('source_folder', 'destination_folder')
```

## Moving and Renaming

### `shutil.move()`

Recursively moves a file or directory (`src`) to another location (`dst`). This is effectively a rename if on the same filesystem.

```python
import shutil

shutil.move('source.txt', 'new_folder/source.txt')
```

## Deleting Directories

### `shutil.rmtree()`

Delete an entire directory tree; `path` must point to a directory (but not a symbolic link to a directory).

```python
import shutil

# Be careful! This deletes everything inside the folder.
shutil.rmtree('folder_to_delete')
```

## Archiving

The `shutil` module provides high-level utilities to create and read compressed archive files (zip, tar, etc.).

### Creating an Archive

```python
import shutil

# Create a zip file 'backup.zip' from the directory 'data'
shutil.make_archive('backup', 'zip', 'data')
```

### Unpacking an Archive

```python
import shutil

shutil.unpack_archive('backup.zip', 'extracted_folder')
```

## Disk Usage

Get disk usage statistics about the given path.

```python
import shutil

total, used, free = shutil.disk_usage("/")

print(f"Total: {total // (2**30)} GiB")
print(f"Used: {used // (2**30)} GiB")
print(f"Free: {free // (2**30)} GiB")
```

[[programming/python/python]]