引言
我在批量转txt文件的时候出现了两种编码的文件混在一起转,导致了本来就是utf-8编码的文件又重新转码了一次,结果就是出现了乱码。
一、基本思路
获取需要改变编码格式的文件夹路径
读取该文件夹下的txt文件,利用第三方库chardet进行编码格式查看,并将该编码格式记录
如果该txt文件被记录的编码与你要跳过的编码不一致,则用utf-8重新编码,重新写入源文件并覆盖,实现转码
二、遇到的问题
1. 由于批量转码的时候可能会遇到,一个文件夹下面的文件不全是一种的编码,所以需要通过chardet进行读取txt文件的编码类型并记录,如果出现问题则可能是文件编码问题。
2. 预测结果为GB2312的文本直接处理,反之跳过。
with open(filePath, "rb") as f:
data = f.read()
a = chardet.detect(data)['encoding']
b = 'GB2312'
if a == b:
convert(filePath, 'GB2312', 'UTF-8')
三、源码
import os
import codecs
import chardet
def list_folders_files(path):
list_folders = []
list_files = []
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
list_folders.append(file)
else:
list_files.append(file)
return (list_folders, list_files)
def convert(file, in_enc="GBK", out_enc="UTF-8"):
"""
该程序⽤于将⽬录下的⽂件从指定格式转换到指定格式,默认的是GBK转到utf-8
"""
in_enc = in_enc.upper()
out_enc = out_enc.upper()
try:
print("convert [ " + file.split('\\')[-1] + " ].....From " + in_enc + " --> " + out_enc)
f = codecs.open(file, 'r', in_enc, "ignore")
new_content = f.read()
codecs.open(file, 'w', out_enc).write(new_content)
except IOError as err:
print("I/O error: {0}".format(err))
if __name__ == "__main__":
print('abc')
path = r'F:\python\txt'
(list_folders, list_files) = list_folders_files(path)
print("Path: " + path)
for fileName in list_files:
filePath = path + '\\' + fileName
with open(filePath, "rb") as f:
data = f.read()
a = chardet.detect(data)['encoding']
b = 'GB2312'
if a == b:
convert(filePath, 'GB2312', 'UTF-8')