LESSON 19 · NEXT STEPS19 min

Reading and Writing Files

open(path, 'w', encoding='utf-8') creates or replaces a text file. open(path, 'r', encoding='utf-8') reads one. The with statement closes each file automatically when its block ends, including when an error occurs.

Write and read a UTF-8 text file with a context manager.

Before you start: Exceptions · Input and Output

Example check: Worked and guided code samples are checked against CPython 3.13. Practice uses Pyodide 0.29.5 (Python 3.13) in your browser. How we check lessons

Video lesson: Reading and Writing Files

The preview is stored on this site. YouTube loads only when you press Play. Watch on YouTube

Read the video transcript

Select a timestamp to watch that moment on YouTube.

  1. 00:00

    A variable holds data while a program runs, but what if you want to read a note back from a file? In this lesson we will write the sentence practice makes progress to a text file, then open that file and print what we saved. The example uses a context manager, explicit text encoding, and two file modes. We will also show what happens when you read before writing and when you use write mode on a file that already has content. One important detail comes first. The Python console on this website uses a browser-based virtual filesystem for the exercise. The note is not being written into your computer's Documents folder.

  2. 00:40

    Write and read it during the same run. If you want to work with a lasting file on your own computer, you will need a local Python installation and a file path on that machine. Begin with the function save note, which accepts the text to store. The first with statement opens practice note dot text in write mode. The letter w means create the file if it does not exist, or replace its contents if it does. State the encoding explicitly as UTF eight so the text is interpreted consistently. The value after as is the file object we use inside the indented block. Call file write with the text. This writes the characters but does not add a newline automatically.

  3. 01:23

    When execution leaves the with block, Python closes the file. We do not need to remember a separate close call, even if an exception occurs inside the block. Now open the same path again, this time with the letter r for read mode and the same encoding. Call file read and return its contents. The print call outside the function displays practice makes progress, matching the original text. Trace those two with blocks in order: write, close, open for reading, read, close, return, print. If you reverse the order and try to read a brand-new path first, Python raises FileNotFoundError because there is nothing to read.

  4. 02:03

    Write mode also has a consequence that is easy to miss. Calling the function a second time with a different note replaces the previous content. The task checker intentionally tests a replacement note to verify this behavior. If the goal is to add new text instead, open in append mode with the letter a. The deeper guide compares write and append modes with a small log. Appending creates the file if needed and adds text at the end, but you must include a newline yourself when you want separate lines. After appending two entries, read the file and predict how the lines appear. Another guide example writes three logical lines and uses file read followed by splitlines to turn them into a list.

  5. 02:48

    The interior blank line remains in that list, while the newline markers are removed. A beginner note is tiny, so reading it all at once is fine. For a much larger file, iterating over the file object would process lines without loading the entire document into one string. File paths also matter. A relative path like practice note dot text is resolved from the program's current working directory. That directory may not be the folder you expected, especially in an editor, a terminal, or a browser sandbox. In a local program, printing the working directory or using an explicit path can help you find a file.

  6. 03:29

    Here the path lives inside the lesson's virtual environment. It may disappear when the browser runtime resets or when the page reloads, so do not use this example as permanent storage. Try an empty string as input. The function creates or replaces the file, writes zero characters, and reads back an empty string. That is a valid boundary case, not an error. Try a note with a line break too. The read method returns the line break as part of the exact contents. Our function does not strip or edit the text. This predictability makes it easy to verify the round trip. The overall pattern is simple: open for the intended action, do the action inside with, and choose encoding and path deliberately.

  7. 04:16

    Those decisions become more important when files are shared across operating systems or contain characters beyond plain English. The first common mistake is opening a new filename in read mode and expecting Python to create it. Read mode requires an existing file, so write first when creating a note. The second is confusing write and append. A second open in write mode clears the previous contents; append mode keeps them and adds more. Say out loud which result you expect before running either version. A third mistake is omitting the with statement and forgetting to close the file. That can leave buffered data unwritten or keep a resource open longer than intended.

  8. 05:01

    The context manager makes closing automatic. Another subtle mistake is assuming this browser's virtual file appears on your computer's disk. The exercise runs in a sandbox; use your local Python installation for real files you want to keep. If you cannot find a local file, check the current working directory rather than guessing where the relative path was resolved. Pause the video and complete save note in the lesson editor. Use one with block to write the text in UTF eight, and another to read the same path. Run the original sentence and compare the returned text character by character with what you passed in.

  9. 05:41

    Then try a note with two lines and predict whether the line break comes back. Use the task checker after your own run. It tests multiline text and then a replacement note, so returning the sample sentence without file operations will not pass. Complete the three-question quiz to finish the lesson. For an optional extension, write two log lines using append mode, then read the file and split it into lines, as the deeper guide demonstrates. When you eventually run this code locally, use a scratch folder so you know exactly which file is created and can inspect it with a text editor. The lesson link on screen includes the browser console, solved examples, expected output, hints, and typical mistakes.

Understand the concept

The browser Python console uses a virtual filesystem. A file you create here is for this browser exercise; it is not a file saved to your computer. Do not rely on it being present after reloading or in a different session. Run both writing and reading in one program.

In the practice task, save_note(text) writes to practice_note.txt, reads the file back, and returns its contents. Calling it again should replace the old contents because 'w' mode overwrites the file. Choose 'a' only when you intentionally want to append.

  • 'w' writes and replaces; 'r' reads; 'a' appends
  • encoding='utf-8' makes text encoding explicit
  • with closes the file automatically

See it step by step

Read the code, predict the output, then compare it with the result.

01. Write and read text

PYTHON
with open("example.txt", "w", encoding="utf-8") as file:
    file.write("Hello, file!")
with open("example.txt", "r", encoding="utf-8") as file:
    print(file.read())
EXPECTED OUTPUT
Hello, file!

The first with block writes text; the second opens the same virtual file and reads it.

02. Overwrite deliberately

PYTHON
with open("status.txt", "w", encoding="utf-8") as file:
    file.write("old")
with open("status.txt", "w", encoding="utf-8") as file:
    file.write("new")
with open("status.txt", "r", encoding="utf-8") as file:
    print(file.read())
EXPECTED OUTPUT
new

Opening with w again replaces the old contents rather than adding to them.

A closer look

Follow the reasoning, inspect each result, then try the suggested changes in the console below.

01 / 03

A filename is resolved from a location

A relative filename such as notes.txt is interpreted relative to the program's current working directory. That directory may differ between an editor, a terminal, and this browser console. When a file is not found, first check which location the program is using. In a larger local program you can build paths from a known project directory rather than guessing where the process was started.

pathlib.Path lets you join path parts without manually typing a slash that differs between operating systems. The code below demonstrates names and suffixes without creating any file. It prints only stable properties, because the full absolute path depends on the machine. In the browser console, any subsequent file creation still happens inside its virtual filesystem.

PYTHON
from pathlib import Path
report = Path("reports") / "weekly.txt"
print(report.name)
print(report.suffix)
print(report.parent.name)
EXPECTED OUTPUT
weekly.txt
.txt
reports
Follow the reasoning
  1. The / operator joins path components; it does not divide numbers here.
  2. name, suffix, and parent describe the path without reading a file.
  3. Change weekly.txt to monthly.csv and predict the first two lines.
02 / 03

Read lines without losing the structure

Reading a whole file with read() gives one string, including newline characters. splitlines() turns that string into logical lines without the line-ending characters. That is convenient for counting or checking entries. Be careful with strip(): it removes whitespace from both ends of a string and might remove meaningful spaces if you are preserving exact source text.

Write and read in one run so this exercise does not depend on a previous console session. The explicit UTF-8 encoding makes the text interpretation clear. The sample includes an empty line on purpose; splitlines keeps that interior blank line. Try deleting the blank line from the written string and predict the number of lines.

PYTHON
with open("guide_lines_demo.txt", "w", encoding="utf-8") as file:
    file.write("first\n\nthird\n")
with open("guide_lines_demo.txt", "r", encoding="utf-8") as file:
    lines = file.read().splitlines()
print(lines)
print(len(lines))
EXPECTED OUTPUT
['first', '', 'third']
3
Follow the reasoning
  1. The first with block creates the file and writes three logical lines.
  2. splitlines removes newline markers but retains the interior empty line.
  3. The second with block closes automatically after reading.
03 / 03

Choose append only when history matters

Opening a file in 'w' mode starts a fresh version; opening in 'a' mode adds to the end. A simple journal or event log may want append, while a generated report often wants write so an old result does not linger. These choices become especially important when a program runs more than once. Always state whether a run should replace or extend earlier data.

This example begins with 'w' so it has a known starting state, then uses 'a' for one more entry. That makes the output deterministic even if a previous run left a file with the same name. A full application may also need to handle a disk error or concurrent writers, but those concerns can wait until the file's intended behavior is clear.

PYTHON
with open("guide_journal_demo.txt", "w", encoding="utf-8") as file:
    file.write("Day 1\n")
with open("guide_journal_demo.txt", "a", encoding="utf-8") as file:
    file.write("Day 2\n")
with open("guide_journal_demo.txt", "r", encoding="utf-8") as file:
    print(file.read(), end="")
EXPECTED OUTPUT
Day 1
Day 2
Follow the reasoning
  1. 'w' resets the file to a known Day 1 entry.
  2. 'a' adds Day 2 rather than replacing Day 1.
  3. Switch the second mode to 'w' and predict the single remaining line.

Try it in Python

Edit the example and run it. Python starts in your browser the first time you click Run.

Python console

Ready to run
Need input()? Add one value per line
Ctrl / ⌘ + Enter to run
OUTPUT
Your output appears here.
Your turnComplete save_note(text). Use with open('practice_note.txt', 'w', encoding='utf-8') to write text, then with open(..., 'r', encoding='utf-8') to read it back and return the file's contents. Keep the sample print line.
Need a hint?

Use one with block to call file.write(text). After it closes, use a second with block and return file.read(). Both blocks use the same filename.

Complete the task and select Check task to verify your code.

    Quick quiz

    Three questions. You can change your answers and try again.

    01.Which mode reads an existing text file?

    02.What does opening a file with 'w' do to existing contents?

    03.Where is a file created by this browser console?

    Typical mistakes

    Everyone meets these errors. See what causes them and how to fix them.

    Reading before writing

    COMMON MISTAKE
    with open('new_note.txt', 'r', encoding='utf-8') as file:
        print(file.read())
    FIX
    with open('new_note.txt', 'w', encoding='utf-8') as file:
        file.write('Ready')
    with open('new_note.txt', 'r', encoding='utf-8') as file:
        print(file.read())

    What happens: FileNotFoundError if the virtual file has not been created in this run.
    Create the file before trying to read it in a fresh exercise run.

    Expecting append from write mode

    COMMON MISTAKE
    with open('note.txt', 'w', encoding='utf-8') as file:
        file.write('second')
    FIX
    with open('note.txt', 'a', encoding='utf-8') as file:
        file.write('second')

    What happens: The old file contents disappear.
    Choose a only when the new text should be added at the end.

    Browse this lesson’s problem fixes

    Sources and further reading