python批处理将utf-8格式文件转为gbk格式

时间:2023-01-10 12:10:24

最近要使用source insight阅读源码,发现源码文件都是utf-8编码的,导致中文注释会出现乱码。所以写了个python批处理文件,批量转换成可以友好阅读的gbk格式。代码如下:

#encoding:utf-8
import os
path_dir = "D:\aiqun\" #这里是要处理的文件所存放的路径,相对路径或者绝对路径都可以
for root, dirs, files in os.walk(path_dir):
for file_name in files:
filename = os.path.join(root, file_name)
content = "".join(open(filename).readlines())
try:
content = content.decode("utf8").encode("gbk") #如果是utf8编码就转成gbk
except:
print "filename not utf8"
continue
f = open(filename, "w")
f.write(content)
f.close()