Python批量轉(zhuǎn)換文件編碼格式
更新時間:2015年05月17日 15:16:29 投稿:hebedich
需要將工作目錄下的文件進行轉(zhuǎn)碼,開始的編碼是GBK的,需要將其轉(zhuǎn)換為utf-8的。文件較多,手動轉(zhuǎn)換肯定不行,用Python寫個腳本來實現(xiàn)。
自己寫的方法,適用于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 #該程序用于將目錄下的文件從指定格式轉(zhuǎn)換到指定格式,默認的是GBK轉(zhuǎn)到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()
以上所述就是本文 的全部內(nèi)容了,希望大家能夠喜歡。
相關(guān)文章
Python數(shù)據(jù)結(jié)構(gòu)之列表與元組詳解
序列是Python中最基本的數(shù)據(jù)結(jié)構(gòu)。序列中的每個元素都分配一個數(shù)字 - 它的位置,或索引,第一個索引是0,第二個索引是1,依此類推,元組與列表類似,不同之處在于元組的元素不能修改。元組使用小括號,列表使用方括號2021-10-10Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字
這篇文章主要介紹了Python神經(jīng)網(wǎng)絡(luò)TensorFlow基于CNN卷積識別手寫數(shù)字的實現(xiàn)示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助2021-10-10回歸預(yù)測分析python數(shù)據(jù)化運營線性回歸總結(jié)
本文主要介紹了python數(shù)據(jù)化運營中的線性回歸一般應(yīng)用場景,常用方法,回歸實現(xiàn),回歸評估指標,效果可視化等,并采用了回歸預(yù)測分析的數(shù)據(jù)預(yù)測方法2021-08-08利用Python實現(xiàn)Shp格式向GeoJSON的轉(zhuǎn)換方法
JSON(JavaScript Object Nonation)是利用鍵值對+嵌套來表示數(shù)據(jù)的一種格式,以其輕量、易解析的優(yōu)點,這篇文章主要介紹了利用Python實現(xiàn)Shp格式向GeoJSON的轉(zhuǎn)換,需要的朋友可以參考下2019-07-07