File Operations – Read, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
File Operations – Read in one minute
What students need to know
readlines() returns a list where each element is one line of the file. Iterating over the file object reads one line at a time. .strip() removes the \n.
read() loads everything at once — fine for small files, memory-hungry for large ones. readline() advances the cursor one line — call it again to get the next.
Mistakes students make
- Missing parentheses read is a method, call it with ().
- Missing parentheses readlines is a method.
- This works but is less efficient. Loop over f directly and use strip().
- Second read() returns '' cursor is at end. Read once or use f.seek(0).
PREVIOUS · MODULE 44File Operations – Open
YOU ARE HERE · MODULE 45File Operations – Read
NEXT · MODULE 46File Operations – Write
What students will learn in this module
Every question in Module 45
Quick questions
- f.read() returns?AOne lineBThe entire file as one string
- f.readlines() returns?AOne stringBA list of all lines
- f.readline() returns?AThe next single lineBAll lines
- Why use line.strip()?ATo remove the \n newline characterBTo split the line
- for line in f: what does this do?ALoops through each lineBReads the whole file
Key terms
Students type the meaning of:
.read().readline().readlines()for line in f:
Match the pairs
with open('f.txt','w') as f:
f.read()Match it to what it doeswith open('f.txt') as f:
f.read()
f.read()Match it to what it doeswith open('f.txt') as f:
lines = f.readlines()Match it to what it doeswith open('f.txt') as f:
for line in f:
print(line.strip())Match it to what it does# file has 'Hello\nWorld' f.readline()Match it to what it does
# file has 'Hi' print(f.read())Match it to what it does
Fill in the blanks
with open('f.txt') as f: content = f.____() print(content)with open('f.txt') as f: lines = f._________()with open('f.txt') as f: first = f.________()for line in f: print(line._____())with open('f.txt') as f: ___ line in f: print(line)
Spot the error
Question 1
Awith open('f.txt') as f:B content = f.readC print(content)
Question 2
Awith open('f.txt') as f:B lines = f.readlinesC print(lines)
Question 3
Awith open('f.txt') as f:B for line in f.readlines():C print(line)
Question 4
Awith open('f.txt') as f:B content = f.read()C content = f.read()D print(content)
Question 5
Af = open('f.txt')Bfor line in f:C print(line)D# forgot to close
