Reading Text Files
Reading a text file means asking Python to open a file and give your program its contents as text.
The smallest version is:
The "r" means read mode. The variable text receives one string containing
the file contents.
For text files you control, specify a text encoding so the same bytes are read the same way across systems:
UTF-8 is the default choice for course data. Later text chapters explain why encoding is a real data decision rather than file-opening decoration.
A file is a source of text
Create a small file, then read it:
Read all text
Ready to run.
repr(text) shows hidden characters such as \n. The second print uses
split to turn whitespace-separated text into a list of strings.
Lines are still strings
You can also read line by line:
Each line is a string. It usually includes the newline at the end. Use
.strip() when you want the content without surrounding whitespace:
clean = line.strip()
Convert near the boundary
Files store text. If the file contains numbers, Python still reads text first.
This conversion is a boundary step: data enters as text, then the program turns it into the type it needs.
Which mode opens a text file for reading?
Answer it first, then check.
HintUse the mode initial
The mode name uses the first letter of “read.”
SolutionUse r mode
The string "r" opens a text file for reading. It does not permit replacing
the file contents.