File Operations – Open, online

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

File Operations – Open in one minute

What students need to know

The with statement automatically closes the file when the block ends. 'a' mode opens the file and adds to the end without erasing existing content.

open() connects your program to a file on disk — you then read or write through that connection. 'r' requires the file to exist — only 'w' and 'a' create files automatically.

Mistakes students make

  • Missing colon after the with statement.
  • open is lowercase: Open is not valid.
  • File is never closed: always close or use 'with'.
  • Can't write in 'r' mode: use 'w' or 'a'.

Discover other journeys with this module

What students will learn in this module

Every question in Module 44

Quick questions

  1. What does open() do?AOpens a websiteBOpens a file for reading or writing
  2. What does 'r' mode mean?ARead onlyBRun
  3. What does 'w' mode do?AWrites overwrites existing contentBReads the file
  4. What does 'a' mode do?AAppends adds to the endBReads all
  5. Why use 'with open()'?AIt's fasterBAutomatically closes the file

Key terms

Students type the meaning of:

  • open()
  • 'r' mode
  • 'w' mode
  • 'a' mode

Match the pairs

f = open('data.txt')
print(f.read())
f.write('hi')
Match it to what it does
open('missing.txt', 'r')Match it to what it does
with open('f.txt', 'r') as f:
    data = f.read()
Match it to what it does
open('f.txt', 'a')Match it to what it does
with open('f.txt','w') as f:
    f.write('Hi')
Match it to what it does
f = open('f.txt','r')
print(type(f))
Match it to what it does

Fill in the blanks

  1. with ____('file.txt', 'r') as f:
  2. with open('file.txt', ___) as f:
  3. with open('file.txt', 'w') __ f:
  4. with open('log.txt', ___) as f:
        f.write('entry')
  5. f = open('test.txt', 'w')
    f.write('Hi')
    f._____()

Spot the error

Question 1

Awith open('file.txt') as fB    content = f.read()C    print(content)Dprint('Done')

Question 2

Awith Open('file.txt') as f:B    content = f.read()C    print(content)Dprint('Done')

Question 3

A# Open without with blockBf = open('file.txt', 'r')Ccontent = f.read()D# forgot to close

Question 4

Awith open('file.txt', 'r') as f:B    f.write('Hello')C    print('Written')Dprint('Done')

Question 5

Awith open(file.txt, 'r') as f:B    content = f.read()C    print(content)Dprint('Done')