Reading and Writing Files
Write and read a UTF-8 text file with a context manager.
Video coming to YouTube
Work through the full lesson and run its code while the video is being prepared for publication.
Understand the concept
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.
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
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())Hello, file!The first with block writes text; the second opens the same virtual file and reads it.
02. Overwrite deliberately
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())newOpening 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.
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.
from pathlib import Path
report = Path("reports") / "weekly.txt"
print(report.name)
print(report.suffix)
print(report.parent.name)weekly.txt
.txt
reports- The / operator joins path components; it does not divide numbers here.
- name, suffix, and parent describe the path without reading a file.
- Change weekly.txt to monthly.csv and predict the first two lines.
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.
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))['first', '', 'third']
3- The first with block creates the file and writes three logical lines.
- splitlines removes newline markers but retains the interior empty line.
- The second with block closes automatically after reading.
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.
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="")Day 1
Day 2- 'w' resets the file to a known Day 1 entry.
- 'a' adds Day 2 rather than replacing Day 1.
- 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 runNeed input()? Add one value per line
Your output appears here.
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.
Typical mistakes
Everyone meets these errors. See what causes them and how to fix them.
Reading before writing
with open('new_note.txt', 'r', encoding='utf-8') as file:
print(file.read())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
with open('note.txt', 'w', encoding='utf-8') as file:
file.write('second')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.