批量文件编码转换工具

代码脚本 · 其他

Python编写的文件编码转换工具,自动识别文件编码(GBK/GB2312/Big5/UTF-8等),批量转换为UTF-8编码,解决中文乱码问题,支持指定文件类型,保留原文件备份,是处理编码问题的实用工具。

详细内容

import chardet, os, glob, shutil def detect_encoding(file): with open(file, 'rb') as f: result = chardet.detect(f.read(100000)) return result['encoding'] input_dir = 'files' for f in glob.glob(os.path.join(input_dir, '*.txt'), recursive=True): enc = detect_encoding(f) if enc and enc.lower() != 'utf-8': print(f'{f}: {enc} -> UTF-8') shutil.copy(f, f + '.bak') # 备份 with open(f, 'r', encoding=enc, errors='replace') as src: content = src.read() with open(f, 'w', encoding='utf-8') as dst: dst.write(content) print('编码转换完成')

适配环境

依赖环境:Python 3.7+,需安装chardet

使用说明

1.安装Python 3.7+
2.pip install chardet
3.保存为convert_encoding.py
4.修改目标文件夹和文件类型
5.python convert_encoding.py 运行
自动识别文件编码
转换前自动备份原文件
可以指定文件扩展名过滤
支持递归子文件夹
已经是UTF-8的文件会跳过

常见问题

问:识别准确率高吗?
答:chardet对常见编码识别率很高,特别是中文GBK/GB2312

问:会损坏文件吗?
答:不会,转换前自动备份原文件,转换失败会恢复

Python编码转换UTF-8GBK乱码批量免费

更多其他