Python implementation of bulk conversion file encoding method

Source: Internet
Author: User
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.

  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.