utf-8转gbk

#! python3
# -*- coding: utf-8 -*-

' utf8togbk '

__author__ = 'guanjianhe'

import sys


def utf8togbk(file):
    content = ''
    try:
        # 以utf-8编码读取
        with open(file, 'r', encoding='utf-8') as fp:
            content = fp.read()

    # 解码错误,则说明不是以utf-8编码,啥都不干
    except UnicodeDecodeError:
        sys.exit()

    else:  # 执行到这里,说明是以utf-8编码,则写入的时候以gbk编码写入
        with open(file, 'w', encoding='gbk') as fp:
            fp.write(content)


if __name__ == '__main__':
    # 这边参数只能有2个,一个是本脚本的参数,另外一个是要转换的文件路径
    if len(sys.argv) == 2:
        utf8togbk(sys.argv[1])
    else:
        pass

编译好的exe文件


转载请注明:guanjianhe的博客 » utf-8转gbk