Errors, files and libraries · Lesson 19 of 25
Reading and writing files
with, encoding and file lifetime.
8 minutes2 games
Use with open(path, mode, encoding="utf-8") as file: so the file closes even if an exception occurs. r reads, w writes from the beginning, and a appends. The example uses a temporary directory; runner files are not persistent storage.
Python
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "notes.txt"
with open(path, "w", encoding="utf-8") as file:
file.write("Hello\nPython")
with open(path, "r", encoding="utf-8") as file:
print(file.read())Open file
Read or write
Exit with
File closes
Quick question
Which mode appends without truncating?
Exercise
Read and print the first line of this in-memory text file without an extra blank line.
Expected output: Python
Python
from io import StringIO
file = StringIO("Python\nHTML\n")
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.