MSIT

Write a line

Open a file with "w" to write. That replaces whatever text was already there. write puts the new text in. Close the file with with, the same way you close a file you read.

Write replaces the old text

Reading uses the default mode. Writing needs a mode. The mode "w" means write. If note.txt already has text, "w" erases that text when the file opens. It does not add the new text after the old text.

write takes a string and puts that string into the file. It does not add a newline unless the string you pass already contains one. If you pass "Hello", the file contains Hello, not Hello plus a blank line.

The file name is still one segment. note.txt is already in the folder. You are replacing its text, not creating a second file and not opening a path with a slash.

The Input and output tutorial states the same rule: 'w' is for writing, and an existing file with the same name will be erased.

A folder icon from the Crystal Clear icon set
"w" replaces the text already stored in the file.
  • "w" opens the file for writing and clears the old text.
  • write puts your string into the file.
  • with closes the file when the block ends, so the new text is finished.

A worked example

note.txt starts as old. save_note("Hello") should leave Hello in the file.

  1. Open note.txt with mode "w" and encoding="utf-8".
  2. Call write with the text argument.
  3. Let with close the file. Do not return the text unless you need it. The check reads the file.

After save_note("Hello"), a later read of note.txt returns "Hello". The word old is gone. Mode "w" replaced it. If you had opened with the default mode, write would not be allowed, because that mode is for reading.

mode can be 'r' when the file will only be read, 'w' for only writing (an existing file with the same name will be erased)

— Python tutorial, Reading and writing files

Mode is the second argument to open. The encoding stays a keyword argument. Do not drop encoding="utf-8" when you add "w".

Pass "w" as the mode. The default mode only reads.

What does mode "w" do to text that is already in the file?

Put the lines in an order that writes text into note.txt.

        handle.delete()
    with open("note.txt", "w", encoding="utf-8") as handle:
        handle.write(text)
def save_note(text):

Exercise

Write a function named save_note that takes text and writes it into note.txt, replacing the old text. The file starts as old.

Write a function named save_note that takes text and writes it into note.txt, replacing the old text.

Output