CKTIS / Python
open()
Ouvre un fichier en flux texte ou binaire.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
open(file, mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)Ouvre un fichier en flux texte ou binaire.
Le mode w crée ou tronque le fichier et UTF-8 explicite code é sur deux octets. La fin du bloc with vide le tampon et ferme le fichier. La réouverture en rb lit c3a9 sans décodage.
Le mode binaire refuse un encodage de texte.
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")
Exemples
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())
Résultat
c3a9
Le mode binaire refuse un encodage de texte.