Python实现文件编码转换GB2312、GBK、UTF-8

Python实现文件编码转换GB2312、GBK、UTF-8


1、查看文件编码格式

import chardet

filename = './flash.c'
with open(filename, 'rb') as f:
    data = f.read()
    encoding_type = chardet.detect(data)
    print(encoding_type)

运行结果:
Python实现文件编码转换GB2312、GBK、UTF-8_第1张图片

2、文件编码转换

预先知道文件编码格式后,UTF-8编码转为GB2312,其他格式转换也是如此,示例代码:

import chardet
import codecs

filename_in = 'flash.c'
filename_out = 'flash_gb2312.c'

# 输入文件的编码类型
encode_in = 'utf-8'

# 输出文件的编码类型
encode_out = 'gb2312'

with codecs.open(filename=filename_in, mode='r', encoding=encode_in) as fi:
    data = fi.read()
    with open(filename_out, mode='w', encoding=encode_out) as fo:
        fo.write(data)
        fo.close()

with open(filename_out, 'rb') as f:
    data = f.read()
    print(chardet.detect(data))

运行结果:
在这里插入图片描述


ends…

你可能感兴趣的:(Python,python,文件编码转换,UTF-8转GBK,UTF-8转GB2312)