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

yipeiwu_com5年前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)

相关文章

简单的Python2.7编程初学经验总结

简单的Python2.7编程初学经验总结

如果你从来没有使用过Python,我强烈建议你阅读Python introduction,因为你需要知道基本的语法和类型。 包管理 Python世界最棒的地方之一,就是大量的第三方程序包...

Python3 Random模块代码详解

描述 random() 方法返回随机生成的一个实数,它在[0,1)范围内。 import random help(random) FUNCTIONS betavariate(a...

python ip正则式

ip正则式为:r'(([12][0-9][0-9]|[1-9][0-9]|[1-9])\.){3,3}([12][0-9][0-9]|[1-9][0-9]|[1-9])' 以下为一个示例...

python实现在函数中修改变量值的方法

和其他语言不一样,传递参数的时候,python不允许程序员选择采用传值还是传引用。Python参数传递采用的肯定是“传对象引用”的方式。 实际上,这种方式相当于传值和传引用的一种综合。如...

python 定时修改数据库的示例代码

当需要定时修改数据库时,一般我们都选择起一个定时进程去改库。如果将这种定时任务写入业务中,写成一个接口呢,定时进程显得有些不太合适?如果需要定时修改100次数据库,常规做法会启动100个...