flowchart TD A["copyfile(src, dst)"] --> B["contents only -- dst must be a FILE path"] C["copy(src, dst)"] --> D["contents + permissions"] E["copy2(src, dst)"] --> F["contents + permissions + timestamps"] G["copytree(src, dst)"] --> H["a whole directory, recursively"] I["move(src, dst)"] --> J["rename if possible, else copy+delete"] D --> K["dst may be a directory -- it copies INTO it"] F --> K J --> K L["rmtree(path)"] --> M["deletes recursively, with no confirmation and no undo"]
What shutil is for
shutil (shell utilities) helps with:
- copying files/folders
- moving files
- removing directory trees
Copying files
import shutil
shutil.copy2("source.txt", "backup_source.txt")copy2 attempts to preserve metadata.
Copying folders
import shutil
shutil.copytree("my_folder", "my_folder_backup", dirs_exist_ok=True)Moving files
import shutil
shutil.move("old/name.txt", "new/name.txt")Deleting folders (danger!)
import shutil
shutil.rmtree("danger_folder")Always do a dry run before destructive operations.
๐งช Try It Yourself
Exercise 1 โ List Files with os.listdir
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 2 โ Join Paths with os.path.join
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.Exercise 3 โ Write and Read a File
Tab indents. Press Escape, then Tab, to leave the editor. Control plus Enter runs the code; Control plus Shift plus Enter submits it.
Output
Press Run to see what your code prints.