> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/language/python/library/shutil.md).

# shutil

### **Copying Files and Directories**

#### **`shutil.copy(src, dst)`**

* Copies a file from `src` to `dst`.
* Preserves the file content but not metadata (permissions, modification times).

**Example:**

```python
import shutil

shutil.copy('source.txt', 'destination.txt')
print("File copied successfully!")
```

***

#### **`shutil.copy2(src, dst)`**

* Similar to `copy()`, but preserves metadata (e.g., timestamps).

**Example:**

```python
import shutil

shutil.copy2('source.txt', 'destination_with_metadata.txt')
print("File copied with metadata!")
```

***

#### **`shutil.copyfile(src, dst)`**

* Copies the content of the file only.
* The destination must be a valid file path (not a directory).

**Example:**

```python
import shutil

shutil.copyfile('source.txt', 'destination_file.txt')
print("Content copied!")
```

***

#### **`shutil.copytree(src, dst, dirs_exist_ok=False)`**

* Recursively copies an entire directory tree from `src` to `dst`.
* Set `dirs_exist_ok=True` to overwrite existing directories (Python 3.8+).

**Example:**

```python
import shutil

shutil.copytree('source_dir', 'destination_dir')
print("Directory tree copied!")
```

***

### **Moving and Renaming Files/Directories**

#### **`shutil.move(src, dst)`**

* Moves a file or directory to a new location.
* Can also rename a file or directory.

**Example:**

```python
import shutil

shutil.move('file.txt', 'new_directory/file.txt')
print("File moved successfully!")
```

***

### **Removing Files and Directories**

#### **`shutil.rmtree(path)`**

* Recursively deletes a directory and its contents.

**Example:**

```python
import shutil

shutil.rmtree('directory_to_delete')
print("Directory removed!")
```

***

### **Archiving and Extracting**

#### **`shutil.make_archive(base_name, format, root_dir)`**

* Creates an archive (e.g., `.zip`, `.tar`) from a directory.
* `format` can be `'zip'`, `'tar'`, etc.

**Example:**

```python
import shutil

shutil.make_archive('archive_name', 'zip', 'source_dir')
print("Archive created!")
```

***

#### **`shutil.unpack_archive(filename, extract_dir)`**

* Extracts an archive into a directory.

**Example:**

```python
import shutil

shutil.unpack_archive('archive_name.zip', 'extracted_dir')
print("Archive extracted!")
```

***

### **File Permissions and Metadata**

#### **`shutil.chown(path, user=None, group=None)`**

* Changes the owner and group of a file or directory.

**Example:**

```python
import shutil

shutil.chown('file.txt', user='new_user', group='new_group')
print("Ownership changed!")
```

***

#### **`shutil.copymode(src, dst)`**

* Copies the permissions of `src` to `dst`.

**Example:**

```python
import shutil

shutil.copymode('source.txt', 'destination.txt')
print("Permissions copied!")
```

***

#### **`shutil.copystat(src, dst)`**

* Copies metadata (e.g., timestamps) from `src` to `dst`.

**Example:**

```python
import shutil

shutil.copystat('source.txt', 'destination.txt')
print("Metadata copied!")
```

***

### **Disk Usage**

#### **`shutil.disk_usage(path)`**

* Returns disk usage statistics as a named tuple (`total`, `used`, `free`).

**Example:**

```python
import shutil

usage = shutil.disk_usage('/')
print("Total:", usage.total)
print("Used:", usage.used)
print("Free:", usage.free)
```

***

### **Other Utilities**

#### **`shutil.which(cmd)`**

* Searches for the command `cmd` in the system’s `PATH` and returns its location.

**Example:**

```python
import shutil

cmd_path = shutil.which('python')
print("Python executable path:", cmd_path)
```

***

### **Temporary Directory Tree Comparison**

#### **`shutil.ignore_patterns(*patterns)`**

* Returns a callable to ignore files matching specific patterns during copy operations.

**Example:**

```python
import shutil

shutil.copytree('source_dir', 'destination_dir', ignore=shutil.ignore_patterns('*.txt', '*.log'))
print("Copied while ignoring specific patterns!")
```

***

### **Error Handling**

#### **`shutil.Error`**

* Raised when an error occurs during file operations (e.g., copying or moving files).

**Example:**

```python
import shutil

try:
    shutil.copy('nonexistent.txt', 'destination.txt')
except shutil.Error as e:
    print("Error:", e)
```

***

### **Functions**

| Function                          | Purpose                                                      |
| --------------------------------- | ------------------------------------------------------------ |
| `shutil.copy(src, dst)`           | Copies a file (content only).                                |
| `shutil.copy2(src, dst)`          | Copies a file with metadata.                                 |
| `shutil.copyfile(src, dst)`       | Copies file content to another file.                         |
| `shutil.copytree(src, dst)`       | Recursively copies a directory tree.                         |
| `shutil.move(src, dst)`           | Moves or renames files/directories.                          |
| `shutil.rmtree(path)`             | Recursively deletes a directory.                             |
| `shutil.make_archive()`           | Creates an archive from a directory.                         |
| `shutil.unpack_archive()`         | Extracts an archive.                                         |
| `shutil.disk_usage(path)`         | Returns disk usage statistics.                               |
| `shutil.which(cmd)`               | Locates the command in the system’s PATH.                    |
| `shutil.copymode(src, dst)`       | Copies file permissions.                                     |
| `shutil.copystat(src, dst)`       | Copies metadata (timestamps) between files.                  |
| `shutil.chown(path, user, group)` | Changes file/directory ownership.                            |
| `shutil.ignore_patterns()`        | Ignores files matching specified patterns during operations. |
