Writing to Files

Use write mode and append mode to save data to files

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Write mode vs append mode

Open a file in "w" mode to write new content. If the file already exists, Python overwrites it completely.

with open("output.txt", "w") as file:
    file.write("Hello, world!\n")

Open a file in "a" mode to add content to the end without deleting what is already there.

with open("output.txt", "a") as file:
    file.write("Another line.\n")

The .write() method

.write() writes a string to the file. It does not add a newline automatically — you must include \n at the end of each line.

file.write("Line 1\n")
file.write("Line 2\n")

Confirming a write

Since writing does not produce visible output, always print() a confirmation message so you know the operation succeeded.

Instructions

Write two lines to a file, then append a third line.

  1. Open notes.txt in write mode using with open("notes.txt", "w") as file:. Inside the block, call file.write("Line 1: Python is fun\n"), then call file.write("Line 2: Files are useful\n").
  2. After the block, call print("notes.txt created.").
  3. Open notes.txt in append mode using with open("notes.txt", "a") as file:. Inside the block, call file.write("Line 3: Appended line\n").
  4. After the block, call print("notes.txt updated.").