Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Đọc/ghi file Unicode (UTF-8) trong Python

Module io hiện được khuyến nghị, tương thích Python 3's open syntax.

Ví dụ

import io

# Đọc UTF-8
with io.open(filename, 'r', encoding='utf8') as f:
    text = f.read()
    # process Unicode text

# Ghi UTF-8
with io.open(filename, 'w', encoding='utf8') as f:
    f.write(text)

Python 3: Dùng built-in open()

# Python 3
with open(filename, 'r', encoding='utf-8') as f:
    text = f.read()

with open(filename, 'w', encoding='utf-8') as f:
    f.write(text)

Lưu ý: Luôn chỉ định encoding='utf-8' (hoặc 'utf8') để tránh phụ thuộc locale/system default.