示例工程 31-io-files-struct-socket-sqlite

31-io-files-struct-socket-sqlite/01-encoding-mistakes/encoding_mistakes.py

python · 0.7 KB

"""演示 UTF-8 字节、错误解码与显式编码读写。"""
 
from __future__ import annotations
 
import tempfile
from pathlib import Path
 
 
def main() -> None:
    text = "你好"
    data = text.encode("utf-8")
    print(f"utf8_bytes: {len(data)}")
    print(f"utf8: {data.decode('utf-8')}")
    try:
        data.decode("ascii")
    except UnicodeDecodeError as exc:
        print(f"ascii_error: {exc}")
    print(f"replace_len: {len(data.decode('ascii', errors='replace'))}")
    with tempfile.TemporaryDirectory() as tmp:
        path = Path(tmp) / "note.txt"
        path.write_text(text, encoding="utf-8")
        print(f"roundtrip: {path.read_text(encoding='utf-8')}")
 
 
if __name__ == "__main__":
    main()