io

open()

Opens a file and returns a file object. Default mode 'r' is text read; use 'rb'/'wb' for binary.

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None)

Parameters

Parameter Purpose
mode 'r' read, 'w' write, 'a' append, 'x' create; add 'b' for binary, '+' for read+write
encoding Text encoding (e.g. 'utf-8') — platform-dependent if omitted
newline Controls universal newlines; use '' for csv module
buffering 0 unbuffered (binary only), 1 line-buffered, >1 buffer size

Examples

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

Text read with explicit encoding

with open('a.bin', 'wb') as f:
    f.write(b'\x00\x01')

Binary write

with open('log.txt', 'a', encoding='utf-8') as f:
    f.write('line\n')

Append text

Gotcha

Default text mode uses the locale encoding (often cp1252 on Windows, utf-8 on Linux) — ALWAYS pass encoding='utf-8' for portable code. Enable PYTHONWARNDEFAULTENCODING to catch missing encoding.

Related built-ins

← All Python built-ins