自己寫的方法,適用于linux,
#!/usr/bin/python #coding=utf-8 import sys import os, os.path import dircache import commands def add(x,y): return x*y def trans(dirname): lis = dircache.opendir(dirname) for a in lis: af=dirname+os.sep+a ## print af if os.path.isdir(af): ## print af trans(af) else: ## print af+"encoding="+fi.name ft = commands.getoutput('file -i '+af) ## print ft if a.find('.htm')==-1 and a.find('.xml')==-1 and ft.find('text/')!=-1 and ft.find('iso-8859')!=-1: print 'gbk'+ft+">"+af commands.getoutput('iconv -ficonv -f gbk -t utf-8 -c -o'+""+af+""+af) trans(os.getcwd())
py2.6以下版本可用代碼
import os,sys def convert( filename, in_enc = "GBK", out_enc="UTF8" ): try: print "convert " + filename, content = open(filename).read() new_content = content.decode(in_enc).encode(out_enc) open(filename, 'w').write(new_content) print " done" except: print " error" def explore(dir): for root, dirs, files in os.walk(dir): for file in files: path = os.path.join(root, file) convert(path) def main(): for path in sys.argv[1:]: if os.path.isfile(path): convert(path) elif os.path.isdir(path): explore(path) if __name__ == "__main__": main()
支持py3.1的版本
import os import sys import codecs #該程序用于將目錄下的文件從指定格式轉換到指定格式,默認的是GBK轉到utf-8 def convert(file,in_enc="GBK",out_enc="UTF-8"): try: print ("convert " +file) f=codecs.open(file,'r',in_enc) new_content=f.read() codecs.open(file,'w',out_enc).write(new_content) #print (f.read()) except IOError as err: print ("I/O error: {0}".format(err)) def explore(dir): for root,dirs,files in os.walk(dir): for file in files: path=os.path.join(root,file) convert(path) def main(): for path in sys.argv[1:]: if(os.path.isfile(path)): convert(path) elif os.path.isdir(path): explore(path) if __name__=="__main__": main()
以上所述就是本文 的全部內容了,希望大家能夠喜歡。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
