因为平时文件编码总是不确定,到最后做完了上面又说转成xxx编码.转来转去的,烦了,干脆自己写个自动转换的程序,想必大家也有此痛苦的经历吧

不 过不只是这个用途的,以前我用palm系统的treo650看电子书的时候,有些html文档下载下来都是utf-8的,palm系统是不支持这个的,要 转换为gb,当然主要是些英文技术文档...以前用软件转过,虽说也是批量,但为了这点小事装个那么大的软件,感觉系统又乱七八糟的..不爽...呵呵

现在只是放出python写的脚本源代码,等有空的时候方便大家将脚本嵌入c++编译成exe档的.当然用py2exe可以直接转换,但是那样修改转换编码就不是很方便了,或者我必须再搞一个ini的配置文件...嵌入c++的好处是大家可以直接修改脚本.呵呵 :-)

放在你要批量转换的文件和文件夹的根目录下就可以了

下面是code:

"""
Put this file in the dir which you want to change file encode
OK, Les's begin
"""
import os
import glob

#set your file dir
FILE_ENCODE_DIR = ""
FILE_ENCODE_DIR_LIST = ["",]
_dir_list_all = [".",]

#specify file list
_specify_file_list = []

#encode & decode setting
DECODE = "shift_jis" #current encode
ENCODE = "utf-8" #your wanna encode

def main(dir_list):
global _specify_file_list

get_dir_son_list(dir_list)
#print _dir_list_all
for dir in _dir_list_all:
specify_file_list = glob.glob("%s/*.html"%(dir))
_specify_file_list.extend(specify_file_list)

encode_file(_specify_file_list)

#get the dir list
def get_dir_son_list(dir_list):
global _dir_list_all
for dir in dir_list:
dir_son_list = [os.path.join(dir, f)
for f in os.listdir(dir)
if os.path.isdir(os.path.join(dir, f))]
#print dir_son_list--add all dir into _dir_list_all
_dir_list_all.extend(dir_son_list)
#recursion
get_dir_son_list(dir_son_list)

def encode_file(specify_file_list):
for file in specify_file_list:
f = open(file)
f.seek(0, 0)
f_content = f.read()

try:
f_content_encode = f_content.decode(DECODE).encode(ENCODE)

try:
f_write = open(file,"w")
f_write.write(f_content_encode)
f_write.close()

except IOError:
print "%s:read only; "% file;

except  Exception, e:
print "%s:There is not right encoding"% file;
f.close()

main(FILE_ENCODE_DIR_LIST)
print "Encoding end"