Python implements batch conversion file encoding (batch conversion encoding example)

Source: Internet
Author: User

Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-
_ Author _ = 'your skyer'

Import OS
Import glob

Class Encoding:
Def _ init _ (self ):
# File Extension
Self. ext = ".*"
# Encoding
Self. srcEncoding = None
Self. dstEncoding = None

Def convertEncoding (self, content, srcEncoding = None, dstEncoding = None ):
Return content. decode (self. srcEncoding). encode (self. dstEncoding)

Def processDirectory (self, args, dirname, filenames ):
Print 'Directory ', dirname
For filename in filenames:
If not OS. path. isdir (dirname + '/' + filename ):
If filename. endswith (self. ext) or self. ext = ".*":
Print 'file', filename
Self. f2f (dirname + '/' + filename)

Def f2f (self, filepath, srcEncoding = None, dstEncoding = None ):
Try:
F1 = open (filepath, 'rb ')
Temp = f1.read ()
F1.close ()
F2 = open (filepath, 'wb ')
F2.write (temp. decode (self. srcEncoding). encode (self. dstEncoding ))
F2.close ()
Print 'transcoding successful'
Except t Exception, e:
Print e


Def colectFileType (self, dirname, fileType ):
For filename in glob. glob (r '*.' + fileType ):
Print filename

Def setExt (self, ext ):
If not ext. startswith ('.'):
Ext = "." + ext
Self. ext = ext

Def setSRC (self, encoding ):
Self. srcEncoding = encoding

Def setDST (self, encoding ):
Self. dstEncoding = encoding

If _ name _ = '_ main __':
Obj = Encoding ()
Print u 'Enter the file type :'
Obj. setExt (raw_input ())
Print U' enter the original file encoding :'
Obj. setSRC (raw_input ())
Print U' enter the object type :'
Obj. setDST (raw_input ())
"Obj. setExt ('html ')
Obj. setSRC ('gbk ')
Obj. setDST ('utf-8 ')"""
Print U' enter the directory where the file is located :'
Path = raw_input ()
OS. path. walk (path, obj. processDirectory, None)

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.