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
| Name | Type | Description |
|---|---|---|
| file | path-like | int | File path or existing integer descriptor. |
| mode | str | Access and text/binary mode; default r. |
| buffering | int | -1 selects defaults, 0 unbuffered binary, 1 line buffering in text writes; larger values specify buffer size. |
| encoding | str | None | Text encoding; not accepted for binary mode. |
| errors | str | None | Text codec error handling policy. |
| newline | str | None | Text newline translation policy. |
| closefd | bool | Whether the stream owns an existing descriptor; must be true for a pathname. |
| opener | callable | None | Optional 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)