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.

Tiny Practice

Read and display message.txt.

Starter template

with open("message.txt", "r", encoding="utf-8") as file:
    message = CHANGE_ME
print(message)
Line-by-line explanation
  1. The file opens in read mode.
  2. The missing part belongs to the file handle.
Hint
  1. Use file.
  2. Call its read method.
  3. Use round brackets.
Show Solution
with open("message.txt", "r", encoding="utf-8") as file:
    message = file.read()
print(message)
Line-by-line explanation
  1. The file is opened safely.
  2. Read returns its text.
  3. The text is displayed after closing.