In this paper, we describe the method of Python implementing batch conversion file encoding. Share to everyone for your reference. Specific as follows:
Here, all the files under one directory are converted from one encoding to another and then saved
Import osimport shutildef Match (config,fullpath,type): flag=false if Type = = ' Exclude ': For item in config[' src ' [' ex Clude ']: if Fullpath.startswith (config[' src ' [' Path ']+os.path.sep+item): flag=true break if type== ' fil ter ': For item in config[' src ' [' filter ']: if Fullpath.endswith (item): Flag=true Break return FLAGD EF conver_file (param): For root, dirs, files in os.walk (param[' src ' [' path ']): for filename in Files:readfile=ro ot+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"% Readfil e) shutil.copy (readfile,outfile) if s: #False and print ("Save") with open (outfile, mode= ' W ', enc oding=param[' dest ' [' EncOding ']) as A_file:a_file.write (s) for dirname in dirs:file=root+os.path.sep+ "%s"%dirname if ' exc Lude ' in param[' src ']: if (Match (Param,file, ' Exclude '): Continue outdir=file.replace (param[' src '] [' PA Th '],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)
Hopefully this article will help you with Python programming.