Python open() Function

Beginner
5 min read
Updated: Nov 2026
3 examples
Built-in

Definition

In Python, open(path, mode) opens a file and returns a file object with methods like read(), write(), and line-by-line iteration. The mode says what you want: "r" read (default), "w" write (replacing the file), "a" append, plus "b" for bytes instead of text.

Always open files in a with statement so they are closed automatically, even if an error happens. For text, pass encoding="utf-8" explicitly; otherwise Python uses a platform-dependent default. The examples write into a folder from the tempfile module, so they never touch your real files.

open() is a built-in function: it lives in the builtins module, so it is always available without an import.

Syntax

Use it in a with block.

python
with open(path, "r", encoding="utf-8") as f:
    text = f.read()

with open(path, "w", encoding="utf-8") as f:
    f.write("hello\n")
CallWhat it does
open(p, encoding="utf-8")Read text (mode "r").
open(p, "w", encoding="utf-8")Write text, replacing the file.
open(p, "a", encoding="utf-8")Append text to the end.
open(p, "rb")Read raw bytes.

Binary modes ("rb", "wb") read and write bytes and take no encoding.

Library declarations
python
open(file, mode="r", buffering=-1, encoding=None, errors=None,
     newline=None, closefd=True, opener=None)

Parameters

ParameterDescription
fileRequired. A path (str or pathlib.Path) or a file descriptor.
modeOptional. "r", "w", "a", "x", with "b" or "t" and "+". Default "r".
encodingOptional. Text encoding; pass "utf-8" for portable results.
newlineOptional. Controls line-ending translation in text mode.

Return Value

Return ValueDescription
file objectA text or binary file object, usable as a context manager.

Python Examples

Example 1 — Write a Text File, Then Read It Back

Create a file in a temporary folder with explicit UTF-8 encoding and read its contents.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "notes.txt")

    with open(path, "w", encoding="utf-8") as f:
        f.write("first line\n")
        f.write("second line\n")

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

    print(repr(text))
    print(os.path.basename(path))

How It Works

  1. Safe location. TemporaryDirectory() creates a throwaway folder and deletes it at the end.
  2. Write mode. "w" creates the file; write() does not add newlines for you.
  3. Read everything. read() returns the whole file as one string; repr() makes the newlines visible.
  4. No absolute path printed. basename() shows only the file name, which is the same on every machine.

Example 2 — Append to a File and Read It Line by Line

Write with print(file=...), append more lines, and number them while reading.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "log.txt")
    with open(path, "w", encoding="utf-8") as f:
        print("start", file=f)
    with open(path, "a", encoding="utf-8") as f:
        f.write("step 1\nstep 2\n")

    with open(path, encoding="utf-8") as f:
        for number, line in enumerate(f, 1):
            print(number, line.rstrip("\n"))

How It Works

  1. print to a file. file=f sends the line, with its newline, into the file.
  2. Append mode. "a" keeps the existing content and adds to the end.
  3. Iterate lines. Looping over a file object yields one line at a time, which is memory friendly.
  4. Strip the newline. Each line ends with "\n"; rstrip("\n") removes it before printing.

Example 3 — Binary Mode, Missing Files, and Closing

Write and read raw bytes, handle a missing file, and confirm that with closes the file.

python
import os
import tempfile

with tempfile.TemporaryDirectory() as folder:
    path = os.path.join(folder, "data.bin")
    with open(path, "wb") as f:
        f.write(bytes([0, 255, 65]))
    with open(path, "rb") as f:
        print(f.read())

    try:
        open(os.path.join(folder, "missing.txt"), encoding="utf-8")
    except FileNotFoundError:
        print("missing.txt does not exist")

    with open(path, "rb") as f:
        print(f.closed)
    print(f.closed)

How It Works

  1. Bytes in, bytes out. Binary mode writes and reads bytes unchanged; 65 shows as the letter A.
  2. No encoding in binary mode. Only text mode takes encoding.
  3. Missing file. Opening a file that does not exist for reading raises FileNotFoundError.
  4. Closed automatically. Inside with the file is open; right after the block it is closed.

Frequently Asked Questions

with open(path, encoding="utf-8") as f: text = f.read(). Loop over f to read line by line.
It closes the file automatically when the block ends, even if an exception occurs.
The default encoding depends on the operating system. Being explicit makes the same file read the same way everywhere.
"w" replaces the file's contents; "a" adds to the end.
Open it with "rb". read() then returns bytes instead of str.

Next: ord()

Unicode code point number of a single character.

ord() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

12 people found this page helpful