在Windows中创建的txt文档的默认编码格式为ANSI,我们可以使用【记事本】打开文档,查看其编码方式。
但是在处理某些程序的时候,我们可能需要特定格式的文档,例如utf-8,因为如果文档不是utf-8格式,那么将会带来一系列的乱码问题,以下是快速转换的python代码:
import os
import codecs
import chardet
# 源文件夹和目标文件夹路径
source_folder = r'D:\pythonprogram\中医古籍文件夹'
target_folder = r'D:\pythonprogram\中医古籍utf8_700册'
# 确保目标文件夹存在
if not os.path.exists(target_folder):
os.makedirs(target_folder)
# 遍历源文件夹中的所有txt文件
for filename in os.listdir(source_folder):
if filename.endswith('.txt'):
# 构建源文件和目标文件的完整路径
source_file = os.path.join(source_folder, filename)
target_file = os.path.join(target_folder, filename)
# 检测文件的编码
with open(source_file, 'rb') as f:
raw_data = f.read()
result = chardet.detect(raw_data)
encoding = result['encoding']
# 以检测到的编码读取源文件,并以utf-8格式写入目标文件
with codecs.open(source_file, 'r', encoding=encoding, errors='ignore') as f_source:
content = f_source.read()
with codecs.open(target_file, 'w', encoding='utf-8') as f_target:
f_target.write(content)
print(f'已转换 {filename} 到 utf-8 格式')
print('所有文件转换完成。')
运行结果: