python实现批量转换文件编码(批转换编码示例)

yipeiwu_com6年前Python基础

复制代码 代码如下:

# -*- coding:utf-8 -*-
__author__ = 'walkskyer'

import os
import glob

class Encoding:
    def __init__(self):
        #文件扩展名
        self.ext = ".*"
        #编码
        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 '转码成功'
        except 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'请输入文件类型:'
    obj.setExt(raw_input())
    print u'请输入文件原始编码:'
    obj.setSRC(raw_input())
    print u'请输入文件目标类型:'
    obj.setDST(raw_input())
    """obj.setExt('html')
    obj.setSRC('gbk')
    obj.setDST('utf-8')"""
    print u'请输入文件所在目录:'
    path = raw_input()
    os.path.walk(path, obj.processDirectory, None)

相关文章

python实现在cmd窗口显示彩色文字

python实现在cmd窗口显示彩色文字

新手小白,一直在为cmd窗口的暗白色文字感到苦恼,在网上找了许多方法(也就那两种吐舌头),现在稍微整理了一下,便于使用。 效果图: import ctypes STD_INPU...

selenium 多窗口切换的实现(windows)

在web应用中,常常会遇见点击某个链接会弹出一个新的窗口,或者是相互关联的web应用 ,这样要去操作新窗口中的元素,这时就需要主机切换到新窗口进行操作。。WebDriver 提供了swi...

用Python将Excel数据导入到SQL Server的例子

使用环境:Win10 x64 Python:3.6.4 SqlServer:2008R2     因为近期需要将excel导入到SQL Serve...

python 实现一个反向单位矩阵示例

python 实现一个反向单位矩阵示例

反向单位矩阵 单位矩阵即对角线为 1,如下: ​ 那么反向的单位矩阵就是反对角线为 1: ​ 左右镜像操作 这里采用 numpy 实现。 方案 1 imp...

关于Python3 lambda函数的深入浅出

我们常常看到一个这样的表达式  A=lambda x:x+1 可能会一头雾水不知道怎么计算 最基本的理解就是 def A(x): return x+1 但是理解程序不会将一个表...