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程序設(shè)計有所幫助。
相關(guān)文章
Django開發(fā)中使用Ueditor上傳圖片遇到的坑及解決
在Django開發(fā)中使用Ueditor上傳圖片時,可能會遇到后端配置不正確的問題,建議在實例化Ueditor后加上serverUrl,這可以在Chrome的F12工具中查看請求的后端配置項,此外,如果需要修改上傳路徑,可以在配置文件中更改路徑,并調(diào)整view.py中的代碼來管理上傳文件2024-09-09
python 虛擬環(huán)境的創(chuàng)建與使用方法
本文先介紹虛擬環(huán)境的基礎(chǔ)知識以及使用方法,然后再深入介紹虛擬環(huán)境背后的工作原理,需要的朋友可以參考下2021-06-06
Python從csv文件中讀取數(shù)據(jù)及提取數(shù)據(jù)的方法
這篇文章主要介紹了Python從csv文件中讀取數(shù)據(jù)并提取數(shù)據(jù)的方法,文中通過多種方法給大家講解獲取指定列的數(shù)據(jù),并存入一個數(shù)組中,每種方法通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧2021-11-11
深入理解Pytorch微調(diào)torchvision模型
PyTorch是一個基于Torch的Python開源機器學(xué)習(xí)庫,用于自然語言處理等應(yīng)用程序。它主要由Facebookd的人工智能小組開發(fā),不僅能夠 實現(xiàn)強大的GPU加速,同時還支持動態(tài)神經(jīng)網(wǎng)絡(luò),這一點是現(xiàn)在很多主流框架如TensorFlow都不支持的2021-11-11

