Exercises
Write Files
3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.
Exercise 1Passed
Write two lines to the file, then read it back and print it.
Python
# write two lines, then print the file
write adds no newline of its own.
with open("notes.txt", "w", encoding="utf-8") as f:
f.write("first\n")
f.write("second\n")
with open("notes.txt", encoding="utf-8") as f:
print(f.read().strip())Exercise 2Passed
Append two more lines without losing the first, then print all three.
Python
with open("log.txt", "w", encoding="utf-8") as f:
f.write("one\n")
# append two and three
Mode "a" adds at the end.
with open("log.txt", "w", encoding="utf-8") as f:
f.write("one\n")
with open("log.txt", "a", encoding="utf-8") as f:
f.write("two\n")
f.write("three\n")
with open("log.txt", encoding="utf-8") as f:
print(f.read().strip())Exercise 3Passed
writelines adds no newlines, so this comes out as one line. Fix it with join.
Python
names = ["Ada", "Grace"]
with open("names.txt", "w", encoding="utf-8") as f:
f.writelines(names)
with open("names.txt", encoding="utf-8") as f:
print(f.read().strip())Build the text yourself with a newline between the names.
names = ["Ada", "Grace"]
with open("names.txt", "w", encoding="utf-8") as f:
f.write("\n".join(names) + "\n")
with open("names.txt", encoding="utf-8") as f:
print(f.read().strip())