File Operations – Read, online

Six activities your students do on their own devices. See who's finished, and their scores.

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).

Discover other journeys with this module

What students will learn in this module

Every question in Module 45

Quick questions

  1. f.read() returns?AOne lineBThe entire file as one string
  2. f.readlines() returns?AOne stringBA list of all lines
  3. f.readline() returns?AThe next single lineBAll lines
  4. Why use line.strip()?ATo remove the \n newline characterBTo split the line
  5. 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 does
with open('f.txt') as f:
    f.read()
    f.read()
Match it to what it does
with open('f.txt') as f:
    lines = f.readlines()
Match it to what it does
with 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

  1. with open('f.txt') as f:
        content = f.____()
        print(content)
  2. with open('f.txt') as f:
        lines = f._________()
  3. with open('f.txt') as f:
        first = f.________()
  4. for line in f:
        print(line._____())
  5. 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