← All lessons

with: the file closes itself

Sign in · Sign up

Lesson 9.2

with opens a file and closes it itself — even if an error happened inside:

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

print(text)
  • as f gives a name to work with inside the block;
  • the block body is indented;
  • close() is no longer needed;
  • after the block the file is already closed — you can't read from f outside.

The checker sets the file name filename and its contents content. Rewrite the reading through with open(...) as f: read the whole file and print the text, then print the length of the text.

Hint

with open(...) as f: closes the file by itself at the end of the block.

Inside the block goes f.read(), while print is already outside. The second line is len of the text you read.