Python 提供了 chardet
模块用于自动识别文本文件编码,并且可以使用 codecs
模块进行编码转换。下面是一个示例程序,可以批量自动识别并转换指定目录下的所有文本文件编码:
import os
import chardet
import codecs
# 要转换的文件夹路径
folder_path = '/path/to/folder'
# 遍历文件夹下所有文件
for filename in os.listdir(folder_path):
file_path = os.path.join(folder_path, filename)
# 判断是否是文本文件
if os.path.isfile(file_path) and filename.endswith('.txt'):
# 自动识别文件编码
with open(file_path, 'rb') as f:
encoding = chardet.detect(f.read())['encoding']
# 转换文件编码
with codecs.open(file_path, 'r', encoding) as f:
content = f.read()
with codecs.open(file_path, 'w', 'utf-8') as f:
f.write(content)
在上面的示例程序中,首先指定要转换的文件夹路径,然后遍历该文件夹下的所有文件,判断是否是文本文件。对于每个文本文件,先使用 chardet 模块自动识别文件编码,然后使用 codecs 模块将文件转换为 utf-8 编码并覆盖原文件。注意,这里使用了 rb 模式读取文件,因为 chardet 模块需要二进制模式读取文件才能进行编码识别。