teluzia.Cloud Engineer · Day 26
CHAPTER 04 · PYTHON FUNDAMENTALS

File I/O and exceptions

4–5 hours including independent practice3 topics
LET’S MAKE THIS SIMPLE

What you’re learning today

Read and write UTF-8 text under a predictable contract, then handle expected failures narrowly. Your lab distinguishes missing input from malformed content and writes a report only after successful validation. This is the foundation for trustworthy log parsing and command-line automation. open returns a file object with a selected mode and encoding. r reads, w truncates or creates, and a appends. A with statement closes the handle when its block ends, including during exceptions. Relative paths depend on the working directory; pathlib can express filesystem operations clearly without changing that rule. Exceptions carry typed failure information. FileNotFoundError identifies an absent path, PermissionError an authorization issue, and ValueError often signals invalid content conversion. Catch only failures the program can meaningfully handle. An except block should preserve or communicate the reason instead of producing a success-shaped default from incomplete data.

Think of it this way

A file handle is an open library book; with closes it reliably; exceptions are specific incident reports rather than a reason to ignore everything.

TOPIC 01 / 03Step by step

File modes and context managers

open returns a file object with a selected mode and encoding. r reads, w truncates or creates, and a appends. A with statement closes the handle when its block ends, including during exceptions. Relative paths depend on the working directory; pathlib can express filesystem operations clearly without changing that rule. with open("input.txt",encoding="utf-8") as handle: text=handle.read() explicitly chooses decoding and closes the handle even if processing later raises an exception inside the block. Explicit mode and encoding prevent accidental truncation or platform-dependent text interpretation and make scripts safer to reuse on different operating systems when users supply files containing non-ASCII characters or previously recorded data today. Opening the input in w mode erases it before reading; verify modes and use distinct input and output paths rather than assuming a context manager protects against choosing the wrong operation in the first place.

WORKED EXAMPLE
with open("input.txt",encoding="utf-8") as handle: text=handle.read() explicitly chooses decoding and closes the handle even if processing later raises an exception inside the block.
Why this matters

Explicit mode and encoding prevent accidental truncation or platform-dependent text interpretation and make scripts safer to reuse on different operating systems when users supply files containing non-ASCII characters or previously recorded data today.

A common trap

Opening the input in w mode erases it before reading; verify modes and use distinct input and output paths rather than assuming a context manager protects against choosing the wrong operation in the first place.

Read all topics in this lesson

A complete reference to revisit alongside the guided steps above.

File modes and context managers

open returns a file object with a selected mode and encoding. r reads, w truncates or creates, and a appends. A with statement closes the handle when its block ends, including during exceptions. Relative paths depend on the working directory; pathlib can express filesystem operations clearly without changing that rule. with open("input.txt",encoding="utf-8") as handle: text=handle.read() explicitly chooses decoding and closes the handle even if processing later raises an exception inside the block. Explicit mode and encoding prevent accidental truncation or platform-dependent text interpretation and make scripts safer to reuse on different operating systems when users supply files containing non-ASCII characters or previously recorded data today. Opening the input in w mode erases it before reading; verify modes and use distinct input and output paths rather than assuming a context manager protects against choosing the wrong operation in the first place.

WORKED EXAMPLE
with open("input.txt",encoding="utf-8") as handle: text=handle.read() explicitly chooses decoding and closes the handle even if processing later raises an exception inside the block.

Why this matters

Explicit mode and encoding prevent accidental truncation or platform-dependent text interpretation and make scripts safer to reuse on different operating systems when users supply files containing non-ASCII characters or previously recorded data today.

A common trap

Opening the input in w mode erases it before reading; verify modes and use distinct input and output paths rather than assuming a context manager protects against choosing the wrong operation in the first place.

Expected exceptions and validation

Exceptions carry typed failure information. FileNotFoundError identifies an absent path, PermissionError an authorization issue, and ValueError often signals invalid content conversion. Catch only failures the program can meaningfully handle. An except block should preserve or communicate the reason instead of producing a success-shaped default from incomplete data. try: count=int(text.strip()) except ValueError: raise ValueError("Input must be one integer") provides clearer context while preserving a non-success outcome for malformed content supplied to the script. Narrow handling keeps programming defects visible and gives callers actionable diagnostics, which prevents an automation report from silently treating a missing or malformed source as a legitimate zero measurement in the final output. A broad except: pass hides interrupts and defects as well as expected input errors; catch specific types and decide whether recovery genuinely fulfills the program’s stated input-and-output contract for the task.

WORKED EXAMPLE
try: count=int(text.strip()) except ValueError: raise ValueError("Input must be one integer") provides clearer context while preserving a non-success outcome for malformed content supplied to the script.

Why this matters

Narrow handling keeps programming defects visible and gives callers actionable diagnostics, which prevents an automation report from silently treating a missing or malformed source as a legitimate zero measurement in the final output.

A common trap

A broad except: pass hides interrupts and defects as well as expected input errors; catch specific types and decide whether recovery genuinely fulfills the program’s stated input-and-output contract for the task.

Safe output and failure contracts

Validate input before overwriting an important output. For more robust workflows, write to a temporary file and replace the destination after successful processing, considering permissions and platform behavior. A CLI should return nonzero on failure. Logging a diagnostic is not equivalent to recovering, and partially written reports need an explicit policy. Read and validate all small fixture lines before report.write_text(...); for large streaming data, document whether partial output is removed, retained with a marker or never committed after a failed run. A defined output policy protects downstream consumers from incomplete results and lets you distinguish a genuinely empty dataset from a job that failed before producing a trustworthy report that other tools might read automatically later. Writing success output before validation completes can leave misleading partial artifacts; separate preparation from publication and test failure cases to confirm the destination reflects only completed work according to the declared contract.

WORKED EXAMPLE
Read and validate all small fixture lines before report.write_text(...); for large streaming data, document whether partial output is removed, retained with a marker or never committed after a failed run.

Why this matters

A defined output policy protects downstream consumers from incomplete results and lets you distinguish a genuinely empty dataset from a job that failed before producing a trustworthy report that other tools might read automatically later.

A common trap

Writing success output before validation completes can leave misleading partial artifacts; separate preparation from publication and test failure cases to confirm the destination reflects only completed work according to the declared contract.

KEEP THESE WITH YOU

Today’s takeaways

Choose encoding and mode explicitly.

Catch specific expected failures.

Publish output only under a defined success policy.

CLOSE THE LOOP

Ready to complete this day?

Verify the practical steps and pass the knowledge check (at least two thirds correct).

Lab steps verifiedKnowledge check passed