Python实现批量转换文件编码的方法
本文实例讲述了Python实现批量转换文件编码的方法。分享给大家供大家参考。具体如下:
这里将某个目录下的所有文件从一种编码转换为另一种编码,然后保存
importos
importshutil
defmatch(config,fullpath,type):
flag=False
iftype=='exclude':
foriteminconfig['src']['exclude']:
iffullpath.startswith(config['src']['path']+os.path.sep+item):
flag=True
break
iftype=='filter':
foriteminconfig['src']['filter']:
iffullpath.endswith(item):
flag=True
break
returnflag
defconver_file(param):
forroot,dirs,filesinos.walk(param['src']['path']):
forfilenameinfiles:
readfile=root+os.path.sep+"%s"%filename
print(readfile)
if'filter'inparam['src']:
ifnot(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%sreaderro"%readfile)
shutil.copy(readfile,outfile)
ifs:#Falseand
print("save")
withopen(outfile,mode='w',encoding=param['dest']['encoding'])asa_file:
a_file.write(s)
fordirnameindirs:
file=root+os.path.sep+"%s"%dirname
if'exclude'inparam['src']:
if(match(param,file,'exclude')):
continue
outdir=file.replace(param['src']['path'],param['dest']['path'])
#print(outdir)
ifnotos.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程序设计有所帮助。