Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 03

Opening Files — open() and with open() as

Open a Python file with open() or with open(), and close it manually or automatically so the saved record stays consistent.

Intermediate25 min
Opening and closing files hero Module 16 Lesson 3 with open

Opening a file gives you a file pointer. Closing it finishes the stream so the record on disk matches what you wrote.

Use the playground at the bottom of this page, then take the quiz.

What you will learn

  • The open(name, mode) call and the file pointer it returns
  • Why close() is required after a plain open()
  • How with open(...) as handle closes the file for you
  • What auto-closeability means when the block ends or an exception occurs

The idea

Two ways to keep the file consistent

There are two approaches.

1. Plain open()

text
handle = open("notebook.txt", "w", encoding="utf-8")

handle is the file pointer. For a text file its type is _io.TextIOWrapper. You must call handle.close() when the work is done. Nothing closes the file for you. If you skip close(), the last buffered write may never reach the file.

2. with open() as

text
with open("notebook.txt", "w", encoding="utf-8") as handle:
    handle.write("Avery Lane\n")

with and as are keywords. The file stays open while Python is inside the indented block. When execution leaves that block — including when an exception is raised — Python closes the file. That behavior is auto-closeability. You do not call close() yourself.

Prefer with for lesson code and for the playground. It is the same idea as finally in exception handling: cleanup still runs.

The mode argument is any mode from the previous lesson: r, w, a, r+, w+, a+, x, or x+.

Example

python
handle = open("notebook.txt", "w", encoding="utf-8")
handle.write("Mina Cole\n")
handle.close()

with open("notebook.txt", "a", encoding="utf-8") as handle:
    handle.write("Rowan Blake\n")

print("closed after with:", handle.closed)

handle.closed is True after the with block, even though the example never calls close() the second time. In the playground, change the written names and run again.

Key takeaways

  • open() returns a file pointer aimed at that file

  • A text pointer is a TextIOWrapper

  • Plain open() needs an explicit close()

  • with open() as closes the file when the block ends

  • Auto-close still happens if the block raises an exception

  • Previous: File Opening Modes

  • Next: write() and writelines()

Loading playground…

Check your understanding

Opening and closing files quiz

open() returns:

1 / 10