python实现字符编码的转换
程序员文章站
2022-04-11 16:51:04
...
开发过程中经常会遇到一些字符编码的问题,于是找了一个转换字符编码的函数
import sys
def filter( srcFile, encode, trgFile ):
error = True
while error:
try:
fs = open( srcFile, encoding = encode )
content = fs.read()
fs.close()
error = False
print( 'Success!' )
except UnicodeDecodeError as ude:
pos1, pos2 = ude.args[2], ude.args[3]
fs = open( srcFile, 'rb' )
content = fs.read()
fs.close()
content = content[:pos1] + content[pos2+1:]
ofs = open( srcFile, 'wb' )
ofs.write( content )
ofs.close()
except:
print( 'Other error happened!' )
break
if __name__ == '__main__':
if len(sys.argv) < 4:
print( 'Usage:' )
print( sys.argv[0] + ' input-file input-encoding output-file' )
else:
filter( sys.argv[1], sys.argv[2], sys.argv[3] )
转载于:https://my.oschina.net/wubiao239/blog/869682
上一篇: python的字符编码问题
下一篇: 字符和编码之间的转换(Python)