encoding 参数详解掌握文件读写时的字符编码设置,告别乱码烦恼
在 Python 中,使用内置函数 open() 打开文本文件时,可以指定 encoding 参数。
它用于声明文件内容所使用的字符编码格式(如 UTF-8、GBK 等),确保程序能正确读取或写入文本。
encoding,Python 会使用系统默认编码(通常为 UTF-8,但 Windows 可能是 cp936/GBK),
这可能导致跨平台运行时出现乱码。
读取一个 UTF-8 编码的文件:
with open('example.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
写入内容并指定编码为 GBK:
with open('output.txt', 'w', encoding='gbk') as f:
f.write('你好,世界!')
UnicodeDecodeErrorencoding 不匹配。'utf-8' 改为 'gbk'),或使用 chardet 库自动检测编码。
encoding 或指定错误。encoding='utf-8'。
encoding='utf-8',并在文件开头添加编码声明(Python 脚本):
# -*- coding: utf-8 -*-
encoding 参数,不要依赖系统默认值。utf-8 编码,除非有特殊需求(如对接老旧系统)。