Python實現(xiàn)批量轉(zhuǎn)換文件編碼的方法
更新時間:2015年07月28日 12:17:40 作者:yak
這篇文章主要介紹了Python實現(xiàn)批量轉(zhuǎn)換文件編碼的方法,涉及Python針對文件的遍歷及編碼轉(zhuǎn)換實現(xiàn)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實例講述了Python實現(xiàn)批量轉(zhuǎn)換文件編碼的方法。分享給大家供大家參考。具體如下:
這里將某個目錄下的所有文件從一種編碼轉(zhuǎn)換為另一種編碼,然后保存
import os import shutil def match(config,fullpath,type): flag=False if type == 'exclude': for item in config['src']['exclude']: if fullpath.startswith(config['src']['path']+os.path.sep+item): flag=True break if type=='filter': for item in config['src']['filter']: if fullpath.endswith(item): flag=True break return flag def conver_file(param): for root, dirs, files in os.walk(param['src']['path']): for filename in files: readfile=root+os.path.sep+"%s" %filename print(readfile) if 'filter' in param['src']: if not (match(param,readfile,'filter')): continue s='' outfile=readfile.replace(param['src']['path'],param['dest']['path']) try : s=open(readfile,encoding=param['src']['encoding']).read() except: print("file %s read erro" % readfile) shutil.copy(readfile,outfile) if s: #False and print("save") with open(outfile, mode='w', encoding=param['dest']['encoding']) as a_file: a_file.write(s) for dirname in dirs: file=root+os.path.sep+"%s" %dirname if 'exclude' in param['src']: if(match(param,file,'exclude')): continue outdir=file.replace(param['src']['path'],param['dest']['path']) #print(outdir) if not os.path.isdir(outdir): os.mkdir(outdir) if __name__ == "__main__": param={'src':{'path':r'D:\work\test\trunk','encoding':'gbk','exclude':['dataa'],'filter':['.php','.html','.htm']}, 'dest':{'path':"f:\\test\\new",'encoding':'utf-8'}} conver_file(param)
希望本文所述對大家的Python程序設計有所幫助。
相關文章
Python RabbitMQ實現(xiàn)簡單的進程間通信示例
這篇文章主要介紹了Python RabbitMQ實現(xiàn)簡單的進程間通信示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-07-07Python random模塊(獲取隨機數(shù))常用方法和使用例子
這篇文章主要介紹了Python random模塊(獲取隨機數(shù))常用方法和使用例子,需要的朋友可以參考下2014-05-05python爬蟲數(shù)據(jù)保存到mongoDB的實例方法
在本篇文章里小編給大家整理的是一篇關于python爬蟲數(shù)據(jù)保存到mongoDB的實例方法,有需要的朋友們可以參考下。2020-07-07PyTorch開源圖像分類工具箱MMClassification詳解
MMClassification是一款基于PyTorch的開源圖像分類工具箱,集成了常用的圖像分類網(wǎng)絡,將數(shù)據(jù)加載,模型骨架,訓練調(diào)參,流程等封裝為模塊調(diào)用,便于在模型間進行轉(zhuǎn)換和比較,也高效簡潔的實現(xiàn)了參數(shù)調(diào)整2022-09-09