在工作中遇到了问题,有一些文件跟现有工程的文件编码方式不同,于是就想到编写代码批量进行转换,刚好,最近再学习python语言,我觉得学好一门语言最好的方式就是实践,所以,决定使用python批量转换文件的编码。
思路就是从一种编码格式转换成另外一种编码。但实际中还是有一种情况,就是在目录中,有些文件是不需要转换的,如果这种时候也统一转换的话,同样会出现乱码,所以这个地方要处理。
#codeing=utf-8
import chardet
import sys,os
def convertEncoding(to_encode,old_filepath):
print old_filepath
f1=file(old_filepath)
text=f1.read();
f1.closed
enc=chardet.detect(text)
print enc
if enc['encoding'] == None :
return
text=text.decode(enc['encoding']).encode(to_encode)
f2=file(old_filepath,'w')
f2.write(text)
f2.close()
def listFiles(fromdir):
for root,dirs,files in os.walk(fromdir):
if len(files)!=0:
for file in files:
convertEncoding("UTF-8",os.path.join(root,file))
if __name__ =="__main__":
listFiles("D:\\WebContent")
这里用到了外部库Chardet,需要另外下载。转换的地方是从检测到的编码类型直接转化为我们要改变的编码类型,这样,就避免了前面说的问题。