Python for Humans · Draft v0.1 · Oct 23, 2026 · Draft position: chapter 4 · First draft of the web edition prototype; prose is placeholder.
Reading a File
- You should already know
- Variables (chapter 2); strings,
len, and abilities like.upper()and.replace()(chapter 3). - You'll build
- All of Shakespeare in the REPL, and an answer to how many times “love” appears.
- You'll be able to
- Read a file into a string, search and count inside it, and split it into words.
- You need
- This page. Python runs in the panel beside it; installing Python on your own computer comes in chapter 11.
Felt problem. Every sentence so far has been one you typed. What if you wanted to work with all of Hamlet, or everything Shakespeare wrote?
Name the general idea. A file is text that lives on disk; a program can pull it into memory as one value.
Python's form
Type these into the Python panel yourself. Don't paste them.
>>> text = open('shakespeare.txt').read() >>> len(text) 5378702 >>> text[:72] 'The Project Gutenberg eBook of The Complete Works of William Shakespeare'
Turn the knob: change 72 to 300 and predict what you'll see. What is \n?
Why is it like this. One sentence: why open() and .read() are two steps.
Build it: how often does Shakespeare say “love”?
>>> text.count('love') 2989 >>> text.count('Love') 182 >>> text.lower().count('love') 3201
Turn the knob: is 2,989 really the number of times he wrote love? Try text.count('glove'), then 'lovely'.
>>> text.find('wherefore art thou') 3962377 >>> text[3962353:3962402] 'JULIET.\nO Romeo, Romeo, wherefore art thou Romeo?'
Because. What .find() hands back, and why the slice starts 24 characters earlier.
Hit a limitation
>>> words = text.split() >>> len(words) 966506 >>> words[:8] ['The', 'Project', 'Gutenberg', 'eBook', 'of', 'The', 'Complete', 'Works']
Limitation, flagged forward. .split() hands you a list: almost a million words you can count but can't yet do much with. Chapter 5.
Exercises
Predict 1
line = 'To be, or not to be' print(line.find('be')) print(line.find('Be'))
Predict 2
You won't guess the exact numbers. Predict this instead: is the third number bigger than, smaller than, or equal to the first two added together?
text = open('shakespeare.txt').read() print(text.count('Romeo')) print(text.count('ROMEO')) print(text.lower().count('romeo'))
Break it 1
This should print how many characters are in the file. Run it, read the error from the bottom up, then fix it.
text = open('shakespeare.txt').read print(len(text))
Break it 2
This one runs without an error, and it's wrong. Fix it. Then decide which number you'd trust, and why.
text = open('shakespeare.txt').read() print('Romeo is mentioned', text.count('romeo'), 'times')
Build it
Count three words of your own choosing. Which surprised you?
Ask it
Write the precise question you'd ask about something in this chapter you don't yet understand.
What I've Learned
One line, in your own words, for your running file.