On this page
codecs.open
Prev: codecs.namereplace_errors | Up: codecs | Next: codecs.register
Rel: codecs.backslashreplace_errors, codecs.Codec, codecs.CodecInfo, codecs.decode
Ref: docs.python.org — codecs.open
Tags: #public #python3 #stdlib #codecs
Import
import codecs
from codecs import open
Signature & Overview
codecs.open(filename, mode='r', encoding=None, errors='strict', buffering=-1)
Open an encoded file using the given mode and return a wrapped version providing transparent encoding/decoding.
Usage
import codecs
from pathlib import Path
import tempfile
with tempfile.TemporaryDirectory() as tmp:
p = Path(tmp) / "a.txt"
with codecs.open(str(p), "w", encoding="utf-8") as f:
f.write("hi")
assert p.read_text(encoding="utf-8") == "hi"
Gotchas
- Legacy: Always prefer built-in
open(path, encoding="utf-8")in Python 3 (codecs.openhas different newline handling and is slower).
REPL Inspect
from codecs import open
help(open)
Linked from
Related notes
- tuts/python3/stdlib_module/codecs/namereplace_errors Linked here; links to this page; shared tags: #codecs, #stdlib
- tuts/python3/stdlib_module/codecs/register Linked here; links to this page; shared tags: #codecs, #stdlib
- tuts/python3/stdlib_module/codecs Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/codecs/backslashreplace_errors Linked here; shared tags: #codecs, #stdlib
- tuts/python3/stdlib_module/codecs/Codec Linked here; shared tags: #codecs, #stdlib
- tuts/python3/stdlib_module/codecs/CodecInfo Linked here; shared tags: #codecs, #stdlib
- tuts/python3/stdlib_module/codecs/decode Linked here; shared tags: #codecs, #stdlib
- tuts/python3/stdlib_module/codecs/encode shared tags: #codecs, #stdlib
- tuts/python3/stdlib_module/codecs/EncodedFile shared tags: #codecs, #stdlib
- tuts/python3/stdlib_module/codecs/getdecoder shared tags: #codecs, #stdlib