Path methods cover the basic operations and the shutil module (*shell utilities*) the higher-level ones: copying or deleting whole trees.
import shutil
import tempfile
from pathlib import Path
with tempfile.TemporaryDirectory() as tmp:
base = Path(tmp)
(base / "data").mkdir()
(base / "data" / "a.txt").write_text("one")
(base / "data" / "b.txt").write_text("two")
shutil.copytree(base / "data", base / "copy") # copies folder and content
shutil.copy(base / "data" / "a.txt", base / "a_copy.txt") # copies a file
(base / "a_copy.txt").rename(base / "renamed.txt") # rename / move
shutil.move(base / "renamed.txt", base / "copy" / "mov.txt")
(base / "copy" / "b.txt").unlink() # delete a file
print(sorted(p.name for p in (base / "copy").iterdir())) # ['a.txt', 'mov.txt']
try:
(base / "copy").rmdir() # only deletes EMPTY folders
except OSError:
print("the folder is not empty") # the folder is not empty
shutil.rmtree(base / "copy") # deletes the folder with everything (no recycle bin!)
print((base / "copy").exists()) # False
| Operation | Tool |
|---|---|
| Create folder | mkdir(parents=True, exist_ok=True) |
| Copy file | shutil.copy(source, target) (copy2 keeps dates) |
| Copy folder | shutil.copytree(source, target) (the target must not exist) |
| Move / rename | path.rename(new) or shutil.move |
| Delete file | path.unlink() |
| Delete empty folder | path.rmdir() |
| Delete folder with content | shutil.rmtree(path) |
- Deleting is permanent: there is no recycle bin. Check the path before calling
rmtree, especially if you built it from user data. renamefails or overwrites depending on the system if the target already exists;shutil.moveis more tolerant and works across different disks.- Before writing a file into a new folder, create the folder with
mkdir(parents=True, exist_ok=True)onpath.parent. - Operations that move several files are written first with the list (
sorted(folder.iterdir())) so you do not modify what you are walking through.
You practice it in Organize by extension, Backup copy and Batch rename.