File system · 3 / 15 Theory

Create, copy, move and delete

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
OperationTool
Create foldermkdir(parents=True, exist_ok=True)
Copy fileshutil.copy(source, target) (copy2 keeps dates)
Copy foldershutil.copytree(source, target) (the target must not exist)
Move / renamepath.rename(new) or shutil.move
Delete filepath.unlink()
Delete empty folderpath.rmdir()
Delete folder with contentshutil.rmtree(path)
  • Deleting is permanent: there is no recycle bin. Check the path before calling rmtree, especially if you built it from user data.
  • rename fails or overwrites depending on the system if the target already exists; shutil.move is 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) on path.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.