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
print()
Writes the given objects to a text stream, converting each with str() and joining with sep. Adds end (newline by default) after the last object.
input()
Reads a line from sys.stdin, strips the trailing newline, and returns it as a string. Optionally writes prompt to stdout first.
str()
Returns a str version of an object. With bytes/bytearray, decodes using encoding.