← Python from Scratch Lesson 76 of 78 · 10 XP

Writing and creating files

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

The mode is set by the second argument of open():

Mode What it does
"r" read (the default)
"w" write: creates the file or erases its old contents
"a" append to the end
"x" create a new file; an error if it already exists
with open("log.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")          # write does NOT add \n by itself
    f.write("second line\n")

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("appended at the end\n")

To write many lines at once: f.writelines(["a\n", "b\n"]) or print(..., file=f) — it adds the line break itself.

Be careful with "w": when you open an existing file in this mode, you immediately wipe it, even if you write nothing. If you don't want to overwrite something important by accident, use "x".

Task. Write a function save_list(path, items) that writes the items of a list to a file, each on its own line. The check will call the function and then read the file.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.