Built-in Functions and Types

open()

Open a path or wrap an existing file descriptor as a stream. Use r for reading, w to truncate or create, x for exclusive creation, a for append, + for updating, and b for binary rather than text. Text streams read and write str; binary streams use bytes-like data. Specify encoding for portable text. A context manager closes the stream even if an exception occurs. Invalid options raise ValueError; missing files and permission failures raise OSError subclasses. Never open uncontrolled paths or use write mode without understanding its destructive effect.

Formal Syntax & Structure

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

Parameters & Attributes

NameTypeDescription
filepath-like | intFile path or existing integer descriptor.
modestrAccess and text/binary mode; default r.
bufferingint-1 selects defaults, 0 unbuffered binary, 1 line buffering in text writes; larger values specify buffer size.
encodingstr | NoneText encoding; not accepted for binary mode.
errorsstr | NoneText codec error handling policy.
newlinestr | NoneText newline translation policy.
closefdboolWhether the stream owns an existing descriptor; must be true for a pathname.
openercallable | NoneOptional callable returning an open file descriptor from path and flags.

Return Value

file object

Text or binary stream according to mode and buffering.

Working Example

Example Snippetpython
# Local filesystem fixture: temporary directory removed automatically.from tempfile import TemporaryDirectoryfrom pathlib import Path
with TemporaryDirectory() as folder:    path = Path(folder) / "notes.txt"    with open(path, "x", encoding="utf-8") as stream:        stream.write("Python\n")    with open(path, encoding="utf-8") as stream:        print(stream.read().strip())    print(stream.closed)
Python Reference