File Operations – Write, online

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

File Operations – Write in one minute

What students need to know

\n adds a newline so the next write starts on a new line. writelines() writes each string from the list — doesn't add newlines automatically.

write() sends text to the file — print() sends it to the screen. Unlike print(), write() is literal — add '\n' to end each line.

Mistakes students make

  • write() only accepts strings: convert number with str().
  • Can't write in 'r' mode: use 'w' or 'a'.
  • No newlines both lines will be on the same line: 'Line 1Line 2'.
  • writelines doesn't add \n: strings run together: 'abc'.

Discover other journeys with this module

What students will learn in this module

Every question in Module 46

Quick questions

  1. What does f.write('Hello') do?AWrites 'Hello' to the fileBPrints 'Hello'
  2. Does write() add a newline automatically?AYes alwaysBNo you must add \n yourself
  3. What does 'w' mode do to existing content?AErases it completelyBKeeps it
  4. How do you write without erasing?AUse 'a' mode (append)BUse 'w' mode
  5. f.write('Hi') returns?A'Hi'B2 (number of characters written)

Key terms

Students type the meaning of:

  • .write(string)
  • .writelines(list)
  • 'w' mode
  • 'a' mode

Match the pairs

with open('f.txt','w') as f:
    f.write(42)
Match it to what it does
with open('f.txt','w') as f:
    pass
f.write('hi')
Match it to what it does
with open('f.txt','w') as f:
    f.write('Hello\n')
Match it to what it does
lines = ['a\n','b\n']
f.writelines(lines)
Match it to what it does
with open('f.txt','w') as f:
    n = f.write('Hi')
print(n)
Match it to what it does
with open('f.txt','w') as f:
    f.write('A')
    f.write('B')
Match it to what it does

Fill in the blanks

  1. with open('f.txt', 'w') as f:
        f._____('Hello')
  2. with open('f.txt', ___) as f:
        f.write('Append this')
  3. f.write('Line 1__')
  4. score = 95
    f.write('Score: ' + ___(score))
  5. lines = ['a\n', 'b\n']
    f.__________(lines)

Spot the error

Question 1

Ascore = 42Bwith open('f.txt', 'w') as f:C    f.write(score)Dprint('Saved!')

Question 2

Adata = 'Hello World'Bwith open('f.txt', 'r') as f:C    f.write(data)Dprint('Written!')

Question 3

Awith open('f.txt', 'w') as f:B    f.write('Line 1')C    f.write('Line 2')

Question 4

Alines = ['a', 'b', 'c']Bwith open('f.txt', 'w') as f:C    f.writelines(lines)Dprint('Written!')

Question 5

Af = open('f.txt', 'w')Bf.write('Hello')C# no close