文件编码
更多精彩内容,请查看文档源码库:youngzhiyong的book书架
- python代码文件编码
- Python中的默认编码格式是ASCII格式,在未修改编码格式时,python2将无法解析中文编码。而python3可以进行正确的解析。
- 在python代码文件开头,使用下面两种方式之一标识当前代码文件的编解码(utf或UTF均可)
#coding:utf-8
#-\*-coding:utf-8-\*-
-
输出文本文件编码
with open("test.txt", "w") as fd: fd.write(test_str) # print(test_str, file=fd)
在一般情况下,使用上述代码方式,比如以文本写模式打开文件,print或write写入即可。
-
读取文本文件编码
with open("test.txt", "r", encoding="utf-8") as fd: content = fd.read()
-
若不了解文本文件的编码情况,可使用开源库检测文本的编码
import chardet filename = "test.py" # 开源库,检测出文件的编码格式 file_encoding = chardet.detect(open(filename, "rb").read())["encoding"] # 使用开源库检测出的编码格式,读取文本文件 with open(filename, "r", encoding=file_encoding) as fd: content = fd.read()
说明
使用print(test_str)
方式能够在终端输出正确的中文,但输出到文件中后,不能跨平台查看,出现中文乱码。因此,我们的文本输出需要指定通用跨平台的编码方式:UTF-8
with open("test.txt", "wb") as fd:
fd.write(test_str.encoding("utf-8"))
或者
with open("test.txt", "w", encoding="utf-8") as fd:
fd.write(test_str)