ANSI 转 UTF-8

ANSI和UTF-8格式都不太了解,各自好像都有好几种,下载了一个库,文件基本都是ANSI格式,linux显示乱码,原来都是在虚拟机一个个的“另存为“完成的,这次文件有点多,因此需要用命令完成。

以下方法不通用,遇到特殊情况再行处理

方法1:

1 iconv -f GBK -t UTF-8 inputfilename -o outputfilename
2 #-f后是源文件编码
3 #-t后是转换成的文件编码格式
4 
5 #icov -l 可以查看所有的编码格式,我尝试使用了 -f ANSI没有用
6 #之所以使用 -f GBK, 完全是因为在用方法2来解决文件格式转化时,尝试了GBK参数,
7 #因此使用了 -f GBK

方法2:

file: ansi2utf8
usage: ansi2utf8 sourcefile------------------>output sourcefile.UTF-8
       ansi2utf8 sourcefile newfilename------>output newfilename
1
#! /usr/bin/python 2 3 import sys 4 import codecs 5 6 if(len(sys.argv) < 2): 7 exit() 8 9 if(len(sys.argv) > 3): 10 exit() 11 12 #get inputfile name 13 inputfile = sys.argv[1] 14 #get system file format 15 sysfiletype = sys.getfilesystemencoding() 16 17 #set outputfilename 18 outputfile = inputfile + '.' + sysfiletype 19 if(len(sys.argv) == 3): 20 outputfile = sys.argv[2] 21 22 #read inputfile content 23 inputfilecontent = open(inputfile).read() 24 #convert inputfile content from format('GBK') to system file format 25 inputfilecontent = inputfilecontent.decode('GBK').encode(sysfiletype) 26 27 def save(filename, contents): 28 fh = open(filename, 'w'); 29 fh.write(contents) 30 fh.close() 31 32 #save the converted content to the outputfile. 33 save(outputfile, inputfilecontent)

附:

引述自:blog.itpub.net/29038506/viewspace-766730

GB2312是中国规定的汉字编码,也可以说是简体中文的字符集编码;GBK是GB2312的扩展,除了兼容GB2312外,它还能显示繁体中文,还有日文的假名“
原文地址:https://www.cnblogs.com/openix/p/3232371.html