CKTIS / Python
io.TextIOBase
TextIOBase définit l’interface des flux de texte qui manipulent des str.
Version : Python 3.14; repository image, production runtime not attested
Syntaxe
io.TextIOBase()TextIOBase définit l’interface des flux de texte qui manipulent des str.
encoding indique l’encodage, errors le traitement des erreurs et newlines les fins de ligne rencontrées en lecture universelle. Sur TextIOWrapper, buffer donne accès au flux binaire. detach() le renvoie et rend l’enveloppe inutilisable. StringIO ne possède pas de tampon binaire et detach() lève io.UnsupportedOperation. TextIOWrapper décode les octets selon l’encodage choisi. En UTF-8, trois appels à read(1) donnent 'é', 'x' puis '' à la fin, même si 'é' occupe deux octets.
tell() peut donner une valeur opaque à transmettre à seek() pour restaurer la position sans la traiter comme un indice de caractère.
import io
with io.TextIOWrapper(io.BytesIO('éx'.encode()),encoding='utf-8') as s:
assert isinstance(s,io.TextIOBase) and s.read(1)=='é'
cookie=s.tell()
assert s.read(2)=='x' and s.read(1)==''
assert s.seek(cookie)==cookie and s.read(1)=='x'
try: s.write(b'x')
except TypeError: pass
else: raise AssertionError
raw=io.BytesIO(b'a\r\n')
s=io.TextIOWrapper(raw,encoding='utf-8',errors='strict',newline=None)
assert (s.encoding,s.errors,s.read(),s.newlines)==('utf-8','strict','a\n','\r\n')
assert s.buffer is s.detach() is raw
try: s.read()
except ValueError: pass
else: raise AssertionError
raw.close()
with io.StringIO() as s:
try: s.detach()
except io.UnsupportedOperation: pass
else: raise AssertionError
Exemples
import io
with io.TextIOWrapper(io.BytesIO("éx".encode()), encoding="utf-8") as stream:
print(isinstance(stream, io.TextIOBase))
print(stream.read(1), stream.read(1), repr(stream.read(1)))
Résultat
True é x ''
tell() peut donner une valeur opaque à transmettre à seek() pour restaurer la position sans la traiter comme un indice de caractère.