前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python实现的简版iconv

python实现的简版iconv

作者头像
py3study
发布2020-01-09 11:00:33
1.9K0
发布2020-01-09 11:00:33
举报
文章被收录于专栏:python3

系统管理中,经常涉及的文件编码就是UTF8和GB1803,下面是实现iconv简化功能(UTF8,GB18030互转)的python代码:

def to_unicode(str_a):    if type(str_a) is unicode:        return str_a    try:        u=str_a.decode('utf-8')        return u    except:        try:            u=str_a.decode('gb18030')            return u        except:            pass    return str_a

def iconv(file,to,from_t='',sep=False):    u'''    sep :是否转换换行符    '''    if os.path.exists(file):        try:            import re            f=open(file,'rb')            lines=f.readlines()            f.close()            new_lines=[]            for v in lines:                if from_t!='':                    s=v.decode(from_t).encode(to)                else:                    s=to_unicode(v).encode(to)                if sep:                    if re.match('utf.*',to,re.I):                        s=re.sub('\r\n$','\n',s,re.I)                    else:#gbk:使用windows换行符                        s=re.sub('\r\n$','\n',s,re.I)                        s=re.sub('\n$','\r\n',s,re.I)                new_lines.append(s)            import shutil            shutil.move(file, file+'.bak')            f=open(file,'wb')            f.writelines(new_lines)            f.close()            return NORMAL        except:            return ERROR    return ERROR

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/08/24 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档