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)

相关文章

Random 在 Python 中的使用方法

Random 在 Python 中的使用方法

1.random.random(): 会随机生成0-1之间的小数 例如: 2.random.uniform(min,max): 会随机生成 min - max 之间的小数,其中min...

python实现给微信公众号发送消息的方法

本文实例讲述了python实现给微信公众号发送消息的方法。分享给大家供大家参考,具体如下: 现在通过发微信公众号信息来做消息通知和告警已经很普遍了。最常见的就是运维通过zabbix调用s...

Pyqt5自适应布局实例

在pyqt5中要做到自适应布局,必须应用Layout类 下面列出类似于 html 中 float 功能的布局方法: 实现原理: PyQt5中的布局中,stretch 属性类似于一个可自适...

python实现windows壁纸定期更换功能

python实现windows壁纸定期更换功能

本文定期更换windows壁纸的python程序,很简单,属于自己写着玩的那种,不提供完美的壁纸切换解决方案。 安装pywin32 extensions 安装python2.7后,然后管...

Python进度条实时显示处理进度的示例代码

前言 在大多数时候,我们的程序会一直进行循环处理。这时候,我们非常希望能够知道程序的处理进度,由此来决定接下来该做些什么。接下来告诉大家如何简单又漂亮的实现这一功能。 如何使用这个类 使...