CKTIS / Python
open()
Opens a file as a text or binary stream according to its mode.
Version: Python 3.14; repository image, production runtime not attested
Syntax
open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)Opens a file as a text or binary stream according to its mode.
Text mode decodes bytes using the selected encoding. Binary mode returns the underlying bytes unchanged.
Text mode w creates or truncates the target and encodes the character é using the explicit UTF-8 encoding. Closing the first with block flushes and closes the stream. Reopening with rb returns the two raw bytes c3 and a9; binary mode does not accept a text encoding parameter.
from tempfile import TemporaryDirectory
from pathlib import Path
with TemporaryDirectory() as d:
p = Path(d) / "x"
with open(p, "w", encoding="utf-8") as f:
assert f.write("é") == 1
with open(p, "rb") as f:
assert f.read() == bytes.fromhex("c3a9")
Examples
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as folder:
path = Path(folder) / "label.txt"
with open(path, "w", encoding="utf-8") as file:
file.write("é")
with open(path, "rb") as file:
print(file.read().hex())
Result
c3a9
Text mode w creates or truncates the target and encodes the character é using the explicit UTF-8 encoding. Closing the first with block flushes and closes the stream. Reopening with rb returns the two raw bytes c3 and a9; binary mode does not accept a text encoding parameter.