国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python批量轉換文件編碼格式

2020-02-23 01:15:57
字體:
來源:轉載
供稿:網友

自己寫的方法,適用于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()

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 农安县| 奉新县| 台州市| 姜堰市| 永修县| 吉木乃县| 若尔盖县| 博乐市| 康乐县| 庆云县| 德州市| 寿光市| 杨浦区| 泸水县| 当阳市| 乌拉特中旗| 儋州市| 建宁县| 阳东县| 都安| 汝阳县| 石林| 宜昌市| 长沙市| 安徽省| 隆尧县| 清徐县| 遂川县| 綦江县| 轮台县| 大安市| 冷水江市| 阿拉尔市| 肥城市| 朝阳县| 任丘市| 鄄城县| 香格里拉县| 蒲城县| 林西县| 四平市|