Python File Streams, Modes and Handles
PCAP objective 5.4 is understand basic input/output terminology, and it is the vocabulary objective for files: stream, handle, mode, text against binary. open() returns an object with a name, a mode and an encoding; the mode letter decides what you may do and whether the file is truncated; and five distinct things can go wrong, each with its own exception.
Files and Streams Guide 23 of 25 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 16 min
open() returns a TextIOWrapper in text mode in Python 3 and the io module is the machinery behind it. Python 2's file type no longer exists. The default encoding for open() is locale-dependent - UTF-8 on this machine - which is why passing encoding= explicitly is good practice.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| RUNNER01 | 192.168.0.27 | Ubuntu 26.04 LTS | Python 3.14.4 - the only machine this path needs | 2 Core | 4 GB | 50 GB |
This guide includes
Use this for the input/output terminology objective. This matters because five different things go wrong when you open a file, each with its own exception - and telling them apart is what the questions ask.
- seeing what
openactually returns - reading the mode letters, and what each one allows
- meeting the five things that go wrong, and their exceptions
- using
with, which closes the handle whatever happens - finding the three streams that are always open
Before you start
-
What open returns
-
The mode letters
-
The five things that go wrong
-
with closes the file whatever happens
-
The three streams that are always open
-
What the exam does with this objective