with open("notes.txt", "r", encoding="utf-8") as file:
text = file.read()Line-by-line explanation
openrequests notes.txt."r"means read mode.- UTF-8 explains how text characters are stored.
as filenames the handle.read()loads the text.
print(text)Line-by-line explanation
- The file has already been closed safely.
textcontains its contents.- 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
- The file opens in read mode.
- The missing part belongs to the file handle.
Hint
- Use
file. - Call its
readmethod. - Use round brackets.
Show Solution
with open("message.txt", "r", encoding="utf-8") as file:
message = file.read()
print(message)Line-by-line explanation
- The file is opened safely.
- Read returns its text.
- The text is displayed after closing.