今天导出csv文件后,使用Office打开后出现乱码。
究其原因,含有中文的文件要保存为utf8-bom格式的才可以。
当然了,转为utf16le-bom的也可以,但是像“,”这种分隔符就不好用了。
下面是python的文件编码转换
#!/usr/bin/python
# -*- coding:utf-8 -*-
import os;
# 下载 https://pypi.python.org/pypi/chardet/
# 拷贝 chardet 目录 到 python/2.7/site-packages 目录下即可
import chardet;
# 改变文件/文件夹下所有文件编码
def encode(path,encoding='UTF-8'):
if os.path.isdir(path):
array = walkfile(path);
for p in array:
encode(p,encoding);
pass
pass
elif os.path.isfile(path):
file = open(path,'r');
data = file.read();
file.close();
info = chardet.detect(data);
if info['confidence']<0.7:
print '未知的文件编码',path,info;
return;
encoded = info['encoding'];
if encoded.upper()==encoding.upper():
# print '已经是UTF-8编码',path;
return;
if encoded.upper()=="ASCII":
# print "ASCII编码",path;
return;
print path,"(",encoded,'->',encoding,")";
data = data.decode(encoded)
data = data.encode(encoding);
file = open(path,'w');
file.write(data);
file.close();
pass
pass
调用方式
encode(filepath,"UTF-8-sig")