Python · Stage 7 – Files and Errors · Lesson 38 of 50

Writing to a File

Save text to a file while choosing whether to replace or append.

with open("note.txt", "w", encoding="utf-8") as file:
    file.write("Remember this")
Line-by-line explanation
  1. Open selects note.txt in write mode.
  2. The with block will close it safely.
  3. write saves the string.
  4. Existing content would be replaced.
with open("note.txt", "a", encoding="utf-8") as file:
    file.write("\nAnother line")
Line-by-line explanation
  1. Append mode preserves earlier text.
  2. \n starts a new line.
  3. The new text is added at the end.