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)