python做图标_python实现的简版iconv

系统管理中,经常涉及的文件编码就是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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值