File Operations – Write, online
Six activities your students do on their own devices. See who's finished, and their scores.
Learning
Understanding
Testing
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'.
PREVIOUS · MODULE 45File Operations – Read
YOU ARE HERE · MODULE 46File Operations – Write
NEXT · MODULE 47Files – Error Handling (try/except)
What students will learn in this module
Every question in Module 46
Quick questions
- What does f.write('Hello') do?AWrites 'Hello' to the fileBPrints 'Hello'
- Does write() add a newline automatically?AYes alwaysBNo you must add \n yourself
- What does 'w' mode do to existing content?AErases it completelyBKeeps it
- How do you write without erasing?AUse 'a' mode (append)BUse 'w' mode
- 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 doeswith open('f.txt','w') as f:
pass
f.write('hi')Match it to what it doeswith open('f.txt','w') as f:
f.write('Hello\n')Match it to what it doeslines = ['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 doeswith open('f.txt','w') as f:
f.write('A')
f.write('B')Match it to what it doesFill in the blanks
with open('f.txt', 'w') as f: f._____('Hello')with open('f.txt', ___) as f: f.write('Append this')f.write('Line 1__')score = 95 f.write('Score: ' + ___(score))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
