Exercises
File Handling
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Write one line to notes.txt and read it back, using with both times.
Python
# write then read
open(name, "w") to write, open(name) to read.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first line\n")
with open("notes.txt", encoding="utf-8") as f:
print(f.read().strip())Exercise 2Passed
Open in a mode that refuses to overwrite an existing file, and report the refusal.
Python
with open("once.txt", "w", encoding="utf-8") as f:
f.write("created")
# now try again without overwriting
Mode "x" raises FileExistsError when the file is already there.
with open("once.txt", "w", encoding="utf-8") as f:
f.write("created")
try:
with open("once.txt", "x", encoding="utf-8") as f:
f.write("again")
except FileExistsError:
print("refused to overwrite")Exercise 3Passed
Read a file that is not there, printing a message instead of crashing.
Python
# read not-there.txt safely
Catch FileNotFoundError rather than checking first.
try:
with open("not-there.txt", encoding="utf-8") as f:
print(f.read())
except FileNotFoundError:
print("no such file")