Python批量轉換檔編碼格式

來源:互聯網
上載者:User
自己寫的方法,適用於linux,

#!/usr/bin/python#coding=utf-8import sysimport os, os.pathimport dircacheimport commandsdef add(x,y): return x*ydef trans(dirname): lis = dircache.opendir(dirname) for a in lis:af=dirname+os.sep+a## print af if os.path.isdir(af):## print aftrans(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 osimport sysimport 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()

以上所述就是本文 的全部內容了,希望大家能夠喜歡。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.