国产探花免费观看_亚洲丰满少妇自慰呻吟_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()

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

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 黔南| 科尔| 卢氏县| 博白县| 山西省| 中山市| 安仁县| 乌兰察布市| 时尚| 新沂市| 张掖市| 蛟河市| 巫溪县| 泽库县| 迭部县| 汉中市| 灵川县| 宁强县| 郑州市| 桃园县| 太康县| 吴江市| 尖扎县| 大港区| 渑池县| 河源市| 青河县| 武夷山市| 黔南| 乐山市| 眉山市| 内乡县| 昔阳县| 镇安县| 沾益县| 建昌县| 资中县| 民勤县| 手游| 米泉市| 瑞金市|