smartyfy.mrindigi.com

Python Master Course V2 — 071. File System Fundamentals

SMARTYFY ACADEMY · PYTHON MASTER COURSE V2 · MODULE 07 · LESSON 071 OF 200

File System Fundamentals

Study time: 60–90 minutes. Prerequisites: functions, modules, exceptions and Lesson 070.

Course hub · Previous lesson 070

Video lesson

Video not yet available. A verified video URL/player can be added here later.

Learning objectives

  • Understand files, directories, absolute and relative paths.
  • Use pathlib for portable path operations.
  • Inspect file metadata without changing the source.
  • Safely create directories and handle missing paths.
  • Build a directory inventory tool with clear error handling.

1. File system concepts

A file stores data; a directory groups files and subdirectories. A path identifies a location. An absolute path starts at a filesystem root, while a relative path is interpreted against the process working directory. Do not assume the working directory is the same as the script’s directory.

pathlib.Path provides readable, cross-platform path manipulation. Joining paths with the / operator is preferable to manually concatenating separators. Checking exists() alone is not a substitute for handling errors because a path may change between inspection and use.

Permissions, symbolic links and directory traversal can create security risks. Never accept arbitrary user-supplied paths for destructive operations without validation and explicit authorization.

Understand File System Fundamentals

A path is a location description, not an open file

Constructing Path("reports") / "summary.txt" only builds a path object. It does not create reports, open summary.txt or check that either exists. Properties such as name, suffix and parent describe that path’s components. Operations such as mkdir, open and stat interact with the filesystem and can fail. Keeping this distinction clear helps separate portable path construction from effects that need a real authorized location.

A relative path is interpreted against the process working directory at the time it is used. Starting the same script from two different directories can therefore read two different data.txt files. Path.cwd() shows that working directory. A source-relative path based on __file__ has a different contract and is unavailable in some interactive contexts. Choose which base the program promises and make it explicit in the instructions.

Use an independent, disposable fixture

Python
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as temporary:
    root = Path(temporary)
    folder = root / "reports"
    folder.mkdir()
    sample = folder / "sample.txt"
    sample.write_text("café", encoding="utf-8")
    print(sample.name)
    print(sample.is_file())
    print(len(sample.read_text(encoding="utf-8")))
    print(sample.stat().st_size)
    print(sample.relative_to(root).as_posix())
Expected output
sample.txt
True
4
5
reports/sample.txt

TemporaryDirectory creates a fresh practice directory and removes it when the with block exits. This example supplies its own parent directory, so it does not depend on another example having run first. The text has four Unicode characters but occupies five UTF-8 bytes because é uses two bytes. The final path is made relative to the fixture root and displayed with forward slashes, producing a stable representation across operating systems.

Check for meaning, then handle the actual operation

exists() answers whether a path exists at that moment; it does not guarantee the next operation will work. A file may disappear, permissions may change, or a path may refer to a directory rather than the expected regular file. Catch errors around the operation that matters. Use FileNotFoundError for a missing file, PermissionError for access denial and broader OSError only when the program has a meaningful way to report other filesystem failures.

Directory enumeration can fail before any entry is yielded. In the inventory project, handle errors from the call to iterdir and from consuming its iterator, not only from stat calls inside the loop. Keep an errors list alongside successful rows instead of printing warnings inside a reusable function. The caller can then decide whether an incomplete inventory is acceptable or should stop the workflow.

Be precise about the safety boundary

A symbolic link points to another path; some ordinary file checks follow it. Skipping links in a practice inventory avoids unintentionally inspecting their targets, but a check followed by a later read is not an atomic security guarantee. Another process could change the filesystem between those operations. Use the teaching inventory only on a trusted practice directory, and do not describe it as a hardened scanner for attacker-controlled trees.

For mastery, explain the difference between path construction, inspection and modification. Test an empty directory, one Unicode file, a missing directory and a directory containing a subdirectory. The first inventory is intentionally shallow; Lesson 074 adds recursive traversal. Keep setup writes separate from the read-only scan so the claim “inventory does not change source files” applies to the scan, not to fixture creation. See the pathlib reference for path and filesystem operations.

2. Progressive runnable examples

Python 3.10+. Run each example separately in a disposable practice folder.

Example A — Build paths

from pathlib import Path
path = Path("reports") / "2026" / "summary.csv"
print(path.name)
print(path.suffix)
print(path.parent.name)

Expected:

summary.csv
.csv
2026

Example B — Current working directory

from pathlib import Path
print(Path.cwd().is_absolute())
print(Path("data.txt").is_absolute())
True
False

Example C — Create a practice directory

from pathlib import Path
folder = Path("smartyfy_practice")
folder.mkdir(parents=True, exist_ok=True)
print(folder.is_dir())
True

This creates a directory in the current working directory. Use a disposable location and avoid overwriting important data.

Example D — Inspect file details

from pathlib import Path
p = Path("smartyfy_practice") / "sample.txt"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("Python", encoding="utf-8")
print(p.is_file())
print(p.stat().st_size)
True
6

Size is measured in bytes; Unicode characters may occupy multiple bytes in UTF-8.

3. Guided project — Read-only directory inventory

Create a report listing regular files in a selected practice directory, with their names and sizes. The tool must not modify or delete scanned files.

from pathlib import Path

def inventory(folder: Path):
    if not folder.is_dir():
        raise ValueError("Expected an existing directory")
    rows, errors = [], []
    try:
        entries = sorted(folder.iterdir(), key=lambda p: p.name)
    except OSError as error:
        return rows, [(str(folder), str(error))]
    for entry in entries:
        try:
            if not entry.is_symlink() and entry.is_file():
                rows.append((entry.name, entry.stat().st_size))
        except OSError as error:
            errors.append((entry.name, str(error)))
    return rows, errors

root = Path("smartyfy_practice")
root.mkdir(exist_ok=True)
(root / "sample.txt").write_text("Python", encoding="utf-8")
rows, errors = inventory(root)
for name, size in rows:
    print(f"{name}: {size} bytes")
for name, message in errors:
    print(f"Skipped {name}: {message}")

Expected in a fresh practice directory:

sample.txt: 6 bytes

Other files in the folder will also be listed. This is an example of environment-dependent output, not a guaranteed complete listing.

Testing: try an empty directory, one file, a nested directory and a missing directory. Check that the inventory never changes the scanned files. Avoid following symlinks when inspecting untrusted paths.

4. Common mistakes and debugging

  • Assuming relative paths refer to the source file’s folder.
  • Using platform-specific path separators unnecessarily.
  • Ignoring PermissionError and other OSError conditions.
  • Confusing file size in bytes with number of characters.
  • Following symlinks or deleting paths without explicit checks.

5. Path and inventory warmup

Try these short original exercises, then use the explained practice below.

Warmup: Find the suffix of archive.tar.gz.

Answer: .gz; use suffixes for both suffixes.

Warmup: Construct a path to reports/monthly.csv.

Answer: Path("reports") / "monthly.csv".

Warmup: Check whether a path is a directory.

Answer: path.is_dir().

Warmup: Modify the inventory to count regular files.

Answer: unpack rows, errors = inventory(root), then count len(rows). Report errors separately; a partial scan is not a complete inventory.

Practice and explained answers

Try each question before opening its answer. Predict code results on paper, then compare them with the explanation.

Optional hint for question 1

Distinguish building a path value from calling a method that touches the filesystem.

1. Does Path("reports") / "summary.txt" create anything?

Answer and reasoning:

No. It constructs a path value. Use mkdir to create directories and an explicit write operation to create file contents. Those later operations have separate failure conditions.

2. Why is café four characters but five UTF-8 bytes?

Answer and reasoning:

Python string length counts its four code points in this example. Encoding uses one byte for c, a and f and two for é. File size measures bytes, not displayed letters.

3. Why can a stat call fail after an exists check succeeded?

Answer and reasoning:

The path or its permissions can change between calls. Handle the stat operation’s exception; a preliminary check cannot reserve the file or guarantee later access.

4. Which exception can be missed by placing try only inside the iterdir loop?

Answer and reasoning:

An error opening or enumerating the directory itself can occur before the body runs. Place the relevant try around enumeration as well as around individual entry inspection.

5. How should the original standalone Example D create its missing parent?

Answer and reasoning:

Python
from pathlib import Path

p = Path("smartyfy_practice") / "sample.txt"
p.parent.mkdir(parents=True, exist_ok=True)
p.write_text("Python", encoding="utf-8")
print(p.stat().st_size)
Expected output
6

The parent directory now exists even when Example C has not run. This writes a practice file, so use a disposable folder; the TemporaryDirectory version avoids collisions with an existing sample.

6. Path fundamentals knowledge check

Choose an answer before opening its explanation.

What does Path.cwd() return? A: current working directory; B: Python version; C: root always; D: home always.

Answer A. It returns the process working directory.

What does Path("a") / "b" do? A: divide numbers; B: join path components; C: delete a; D: open b.

Answer B. pathlib overloads / for joining paths.

Which method checks for a directory? A: is_file; B: suffix; C: is_dir; D: stem.

Answer C. is_dir identifies directories.

What does stat().st_size measure? A: characters; B: lines; C: records; D: bytes.

Answer D. File size is expressed in bytes.

Why handle OSError after checking exists()? A: paths and permissions can change; B: Python forbids checks; C: it deletes files; D: it guarantees success.

Answer A. Filesystem state can change between operations.

7. Mastery checkpoint

Explain relative versus absolute paths, build portable paths, safely inspect directory contents and test a missing-path case. The next lesson will cover reading text files. Learner completion is not synchronized to an account by this page.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.