← All lessons

open and read: reading a file

Sign in · Sign up

Lesson 9.0

open opens a file, read reads all of its contents:

f = open("notes.txt", encoding="utf-8")
text = f.read()
f.close()

print(text)

Three steps: open, read, close. If you forget close(), the file stays open, and on Windows you also can't rename or delete it.

open without a mode opens the file for reading — that's what you need here. You can also read it like this:

print(open("notes.txt", encoding="utf-8").read())

The check sets the file name filename and its contents content; the file is already next to the program. The task is different: you don't need to open notes.txt as it is written there. Read the whole file filename, close it and print the text, then print the length of the text with len.

Hint

Open, read, close — three lines in a row.

open(filename, encoding="utf-8") with no second argument only reads. The text comes from .read(), the length is len(...) of what you read.