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

Reading a File

Open a text file safely and read its contents.

with open("notes.txt", "r", encoding="utf-8") as file:
    text = file.read()
Line-by-line explanation
  1. open requests notes.txt.
  2. "r" means read mode.
  3. UTF-8 explains how text characters are stored.
  4. as file names the handle.
  5. read() loads the text.
print(text)
Line-by-line explanation
  1. The file has already been closed safely.
  2. text contains its contents.
  3. Print displays those contents.