txt文档编码转换为utf-8格式-Python代码

在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('所有文件转换完成。')

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值