Python File Reading and Writing
PCAP objective 5.5 is perform input/output operations. There are four ways to read a text file and they differ in what they give you and how much memory they use; readlines and iteration both hand you lines with their newlines attached; and a second read() returns an empty string because the file position is already at the end. That last one accounts for most "why is my file empty?" questions.
Files and Streams Guide 24 of 25 Intermediate
- OSUbuntu 26.04 LTS
- Python3.14.4
- pip25.1.1
- TimeAbout 17 min
Unchanged in Python 3, except that iterating a file yields str in text mode and bytes in binary. file.next() from Python 2 is gone; next(f) is the Python 3 form and is rarely needed.
| 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 file-operations objective. This matters because every line you read still carries its newline, and a handle remembers where it is - so a second read of the same file gives you nothing.
- writing a file, and reading it back four ways
- finding the newline that comes with every line
- seeing the file position, and the empty second read
- counting lines, words and characters in one pass
- handling the file that is not there
Before you start
-
Writing a file
-
The four ways to read it back
-
The newline that comes with every line
-
The file position, and the empty second read
-
Counting, which is the standard exercise
-
Handling the file that is not there
-
What the exam does with this objective