大家使用python操作文件的时候肯定会运到编码不对的情况,我们来看看怎么解决这些问题:
新建一个”a.txt“文件
import chardet
def other_to_utf8():
with open("a.txt", 'r') as f:
data = f.read()
with open("a.txt", "rb") as g:
detect_data = g.read()
print(chardet.detect(detect_data)['encoding'])
with open('a.txt', 'w', encoding='utf-8') as h:
h.write(data)
def utf8_to_other():
with open('a.txt', 'r', encoding="utf-8") as f:
data = f.read()
#data = data.encode("gbk") #"xxx"为你想转换的格式
with open('a.txt', 'w', encoding='gbk') as g:
g.write(data)
with open("a.txt", "rb") as g:
detect_data = g.read()
print(chardet.detect(detect_data)['encoding'])
这仨行用来查询文件的编码格式
with open("a.txt", "rb") as g:
detect_data = g.read()
print(chardet.detect(detect_data)['encoding'])