Skip to content
Foxipa
Code Completion 4 Challenges

Complete the shutil file-operation code

Practise copying files, excluding unwanted tree entries, moving a file, and extracting a tar archive with the data filter.

Intermediate ~10 min read

Challenge 1

Copy the source file to the exact destination path while attempting to preserve available metadata.

python Your answer
from pathlib import Path
import shutil
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    root = Path(folder)
    source = root / "source.txt"
    destination = root / "copy.txt"
    source.write_text("copy me", encoding="utf-8")
    
    assert destination.read_text(encoding="utf-8") == "copy me"
    print(destination.name)

Press Ctrl⌘Enter to check your answer

Challenge 2

Copy the directory tree but skip entries whose names match *.tmp.

python Your answer
from pathlib import Path
import shutil
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    root = Path(folder)
    source = root / "source"
    source.mkdir()
    (source / "keep.txt").write_text("keep", encoding="utf-8")
    (source / "cache.tmp").write_text("skip", encoding="utf-8")
    backup = root / "backup"
    
    assert (backup / "keep.txt").exists()
    assert not (backup / "cache.tmp").exists()
    print("filtered copy complete")

Press Ctrl⌘Enter to check your answer

Challenge 3

Move the source file into the destination directory and assign no unnecessary manual copy/delete steps.

python Your answer
from pathlib import Path
import shutil
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    root = Path(folder)
    source = root / "inbox.txt"
    destination_dir = root / "done"
    destination_dir.mkdir()
    source.write_text("ready", encoding="utf-8")
    
    assert not source.exists()
    assert (destination_dir / "inbox.txt").read_text(encoding="utf-8") == "ready"
    print("move complete")

Press Ctrl⌘Enter to check your answer

Challenge 4

Extract the known tar-based archive to the new destination using the data extraction filter.

python Your answer
from pathlib import Path
import shutil
from tempfile import TemporaryDirectory

with TemporaryDirectory() as folder:
    root = Path(folder)
    project = root / "project"
    project.mkdir()
    (project / "note.txt").write_text("restore me", encoding="utf-8")
    archive = shutil.make_archive(str(root / "backup"), "gztar", root_dir=str(project))
    destination = root / "restored"
    destination.mkdir()
    
    assert (destination / "note.txt").read_text(encoding="utf-8") == "restore me"
    print("archive restored")

Press Ctrl⌘Enter to check your answer