utf8文件转换器

从网上下下来的代码,一编译老是出现:
warning C4819: The file contains a character that cannot be represented in the current code page (936). Save the file in Unicode format to prevent data loss
另我感觉实在不爽得很,因为就一个头文件,就出现几百个这样的警告。采用warning disable的方式应该也不怎么好,所以写了个utf8文件转换器。
用c++做这玩意,实在没意思,大才小用,所以用python做了一个。
import chardet
import tempfile
import os
import shutil
import sys
def convertUtf8(filename):   
  f=open(filename,'r')     
  t=''         #存放文件的数据
  try:
   for line in f:
     t+=line              #所文件读到t里面
  finally:
    f.close()
  encodeing =chardet.detect(t)['encoding']
  if not encodeing =='utf-8':
     print 'file encode',encodeing
     wf=open(filename,'wr')
     wf.write(unicode(t,encodeing).encode('utf-8'))  #编码
     wf.close()
 
if __name__=="__main__":
   filename = sys.argv[1]         #第一个参数为文件名
   convertUtf8(filename)
 
如果你也有我这样烦恼就用用吧。
lixiaomail
2008-07-23
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值