复制代码 代码如下:
# -*- 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,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,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实现批量转换文件编码(批转换编码示例)全部内容,希望文章能够帮你解决python实现批量转换文件编码(批转换编码示例)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)