Python 3 reference · Built-in Functions

Python open() Function

Open a file and return a file object for reading or writing text or bytes. Use it in a with block so it closes automatically.

Python 3 Since 3.0

Syntax

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

Parameters

ParameterDescription
file A path (string or pathlib.Path) or a file descriptor.
mode optional "r" read, "w" write (truncate), "a" append, "x" create; add "b" for binary or "+" for read/write. Default: "r"
encoding optional Text encoding, e.g. "utf-8". UTF-8 is the default since Python 3.15.
buffering, errors, newline, closefd, opener optional Advanced options.

Return value

A file object (text or binary depending on the mode).

Examples

Write, then read line by lineTry it yourself
with open("notes.txt", "w", encoding="utf-8") as f:
    f.write("first line\n")
    f.write("second line\n")

with open("notes.txt", encoding="utf-8") as f:
    for line in f:
        print(line.rstrip())

Output

first line
second line
Append to a fileTry it yourself
with open("log.txt", "w") as f:
    f.write("start\n")
with open("log.txt", "a") as f:
    f.write("more\n")
print(open("log.txt").read())

Output

start
more
Binary filesTry it yourself
with open("data.bin", "wb") as f:
    f.write(bytes([1, 2, 255]))
with open("data.bin", "rb") as f:
    print(f.read())

Output

b'\x01\x02\xff'

Common mistakes

  • Always use with open(...) as f: so the file is closed even if an error happens.
  • Mode "w" erases the file first. Use "a" to add to it, or "x" to fail if it already exists.
  • Before Python 3.15 the default encoding depended on the operating system (often not UTF-8 on Windows); pass encoding="utf-8" explicitly for portable code.
  • Examples here use an in-memory file system, so the files disappear after the run.

Version history

VersionChange
Python 3.0Added
Python 3.15UTF-8 is the default encoding when encoding isn't given (PEP 686).