KennisbankExamencentrum
NL · NLNederlands (Nederland)
Taal kiezen13

CKTIS / Python

open()

Opent een bestand als tekst- of binaire stroom.

Versie: 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)

Opent een bestand als tekst- of binaire stroom.

Modus w maakt het bestand of leegt het en expliciete UTF-8 codeert é in twee bytes. Het einde van with leegt de buffer en sluit het bestand. Heropenen in rb leest c3a9 zonder decodering.

Binaire modus accepteert geen tekstcodering.

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")

Voorbeelden

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())

Resultaat

c3a9

Binaire modus accepteert geen tekstcodering.

Bronnen