Skip to content
Foxipa
Code Completion 5 Challenges

Complete the filesystem metadata code

Practise querying stat results, interpreting mode bits, inspecting links, and handling expected filesystem errors.

Intermediate ~12 min read

Challenge 1

Read the size in bytes from the stat result.

python Your answer
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    path = Path(temporary) / "report.txt"
    path.write_text("report", encoding="utf-8")
    info = path.stat()
    size = info.
    print(size)

Press Ctrl⌘Enter to check your answer

Challenge 2

Use stat module helper to test the file mode.

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

with TemporaryDirectory() as temporary:
    path = Path(temporary) / "report.txt"
    path.write_text("report", encoding="utf-8")
    info = path.stat()
    is_regular = stat.(info.st_mode)
    print(is_regular)

Press Ctrl⌘Enter to check your answer

Challenge 3

Use the no-following metadata query on this path.

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

with TemporaryDirectory() as temporary:
    path = Path(temporary) / "shortcut"
    path.write_text("target", encoding="utf-8")
    info = os.(path)
    print(info.st_size)

Challenge 4

Complete the call that reads metadata from an open file descriptor.

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

with TemporaryDirectory() as temporary:
    path = Path(temporary) / "report.txt"
    path.write_text("report", encoding="utf-8")
    with path.open("rb") as stream:
        info = os.(stream.fileno())
        print(info.st_size)

Press Ctrl⌘Enter to check your answer

Challenge 5

Catch the expected specific exception when the path does not exist.

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

with TemporaryDirectory() as temporary:
    missing = Path(temporary) / "missing-file.txt"
    try:
        os.stat(missing)
    except  as error:
        print(type(error).__name__)

Press Ctrl⌘Enter to check your answer