[python] 批量替换文件夹下的文件编码格式


import chardet
import os

filename = 'H:\\python\\source' #文件夹路径
Aim_Format = 'utf-8' #目标编码格式
code_ifo = 'xxx'

#保存文件
def write_file(content, file):
    with open(file, 'wb') as f:
        f.write(content)

#遍历文件夹下所有文件
def get_filelist(dir, file):
    newDir = dir
    if os.path.isfile(dir):
        file.append(dir)
        Encoding_Format_Trans(dir, Aim_Format)#修改编码格式
    elif os.path.isdir(dir):
        for s in os.listdir(dir):
            newDir = os.path.join(dir, s)
            get_filelist(newDir, file)
    return file

#获取单个文件的编码信息
def get_file_info(file):
    f = open(file, 'rb')
    data = f.read()
    return chardet.detect(data)['encoding'].strip()  #空文本会报错

#编码格式转换
def Encoding_Format_Trans (path_name_, _Aim_Format):
    code_ifo = get_file_info(path_name_)
    print('before ', code_ifo)
    if code_ifo != _Aim_Format:
        if code_ifo == 'GB2312': #gbk的字符集更全,能解一些2312为乱码的文字
            code_ifo = 'gbk'
        f = open(path_name_, 'rb')
        file_decode = f.read().decode(code_ifo, 'ignore') #编码的字符---> unicode
        file_encode = file_decode.encode(_Aim_Format) #unicode-->目标编码格式
        write_file(file_encode, path_name_)
        code_test = get_file_info(path_name_)
        print('after ', code_test)



if __name__ == "__main__":
    list = get_filelist(filename, [])
    print('over')

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值