一、系统默认的编码格式为utf8

二、读写文件时通过参数encoding='utf8'指定编码格式,否则文件在本地打开时会乱码(与系统默认编码不符,参考第1条)

三、实例①,设置编码格式为utf8,本地打开和程序读取都展示正常,无乱码:

text = '我是XX,我爱python'
f = open("a.txt", 'w', encoding='utf8')
f.write(text)
# 将数据写入磁盘文件
f.flush()

f_read = open('a.txt', encoding='utf8')
res = f_read.read()
print(res)

python 检测文件编码 python读文件编码_默认编码

 四、实例②,设置编码格式为gbk,程序读取都展示正常,本地打开乱码,因为与系统默认编码格式utf8不符:

text = '我是XX,我爱python'
f = open("a.txt", 'w', encoding='gbk')
f.write(text)
f.flush()

f_read = open('a.txt', encoding='gbk')
res = f_read.read()
print(res)

 

python 检测文件编码 python读文件编码_编码格式_02