Chapters
Python114 chapters

Exercises

Write Files

3 tasks. Write the code, press Check, and the page runs it against a real Python interpreter.

Exercise 1

Write two lines to the file, then read it back and print it.

Python
# write two lines, then print the file
Exercise 2

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
Exercise 3

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())