10/25/26About 2 minAbout 305 words
Concept: Creating, moving and deleting files and directories
The shutil module provides a high-level interface for file operations. It can be used to copy, move and delete files and directories as well as to create archives (but the zipfile and tarfile modules are preferred).
| Function | Description | Example |
|---|---|---|
| shutil.copy(src, dst) | Copies a file from src to dst. | shutil.copy("file.txt", "backup/file.txt") |
| shutil.copy2(src, dst) | Copies a file from src to dst and preserve as much metadata as possible. | shutil.copy2("file.txt", "backup/file.txt") |
| shutil.copytree(src, dst) | Copies a directory and it's contents from src to dst. | shutil.copytree("dir", "backup/dir") |
| shutil.move(src, dst) | Recursively moves a file or directory from src to dst. | shutil.move("file.txt", "backup/file.txt") |
| shutil.rmtree(path) | Recursively deletes a directory and it's contents. | shutil.rmtree("dir") |
| shutil.which(cmd) | Returns the path of an executable or None if not found. | shutil.which("python") |
| shutil.chown(path, user=None, group=None) | Changes the owner and/or group of a file or directory for a file on a *nix filesystem. | shutil.chown("file.txt", user="sebastiaan") |
The shutil module has two important problem, it cannot be used to delete a single file, only directories and it cannot be used to create directories. For that the pathlib module can be used.
| Function | Description | Example |
|---|---|---|
| Path.unlink() | Deletes a file. | Path("file.txt").unlink() |
| Path.rmdir() | Deletes an empty directory. | Path("dir").rmdir() |
| Path.mkdir(path, parents=False, exist_ok) | Creates a single directory (including non-existing parents when parents=True) | Path("dir").mkdir() |