</>
Skip to content
Python lessons (38/45)

Python — File Open

open() — the gateway

f = open("notes.txt")          # default mode "r" = read text
content = f.read()
f.close()                      # must remember!

with — the only way you should open files

The context manager closes automatically, even on errors:

with open("notes.txt") as f:
    content = f.read()
# file closed here — no matter what happened inside

Never write manual open/close in real code; with is the idiom.

The mode argument

ModeMeaning
"r"read (default) — fails if missing
"w"write — erases existing content!
"a"append to the end
"x"create new; fail if exists
"r+"read + write
"rb" / "wb"raw bytes (images, binaries)
with open("log.txt", "a") as f:    # append, don't clobber
    f.write("new entry\n")

Encoding — set it explicitly

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

Windows defaults differ from other OSes; declaring utf-8 makes files portable and keeps é/中/emoji intact.

Missing files raise

try:
    with open("ghost.txt") as f:
        print(f.read())
except FileNotFoundError:
    print("No such file")

Listing a folder

import os

os.listdir(".")                       # names only

from pathlib import Path              # the modern path API
for p in Path(".").glob("*.txt"):
    print(p.name)

pathlib.Path is preferred for anything beyond quick scripts:

path = Path("data") / "users.csv"     # OS-safe joining
path.exists()

Paths & locations

Path("notes.txt").resolve()      # absolute location
Path.home()                      # user's home dir

Gotchas: "w" truncates instantly on open · relative paths depend on WHERE you ran Python, not where the script lives (Path(__file__).parent anchors it) · forgetting encoding → mojibake on Windows.

Mini Practice

  1. Read any .py file; print its line count.
  2. Append three lines; reopen and verify.
  3. Trigger FileNotFoundError; catch it gracefully.
  4. List all .md files in a folder via pathlib glob.
  5. Prove "w" erases: write, reopen with w, check empty.

Next: read files →

Related Topics

Frequently Asked Questions about File Open

What is File Open in Python?

File Open is a fundamental concept in Python. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn File Open?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn File Open.

Why is File Open important in Python?

File Open is essential for Python development. Understanding this concept will help you write better code and solve real-world problems more effectively.