文件夹下所有utf8文件转ANSI文件

本文介绍了一个使用Python编写的脚本,该脚本可以将指定文件夹内的.c和.h文件从UTF-8编码转换为GB18030编码。通过读取文件内容并检查其当前编码是否为UTF-8,如果是,则进行转换并覆盖原文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import codecs
import chardet
import sys
reload(sys)
sys.setdefaultencoding('utf-8')  #如果没有这部分,WriteFile会报错

def RedaFile(filename,encoding="utf-8"):
    with codecs.open(filename,"r") as f:
        content = f.read()
        f.close()
        if chardet.detect(content)["encoding"] == encoding:    #只转utf8编码的
            return content
        else:            
            return None

def WriteFile(filename,content,encoding="gb18030"):
    with codecs.open(filename,"wb",encoding) as f:
        f.write(content)
        f.close()
    
    
def utf8_to_ansi(src,dst):
    content = RedaFile(src,encoding="utf-8")
    if content:
        WriteFile(dst,content,encoding="gb18030")
        print "change file is %s"%dst
    
def FilesFormat(path):
    for root, dirs, files in os.walk(path):
        for f in files:
            if f[-2:] == '.c' or f[-2:] == '.h':          #只转.c和.h文件
                utf8_to_ansi(root+"\\"+f, root+"\\"+f)       #新文件覆盖旧文件        
                
if __name__ == "__main__":
    FilesFormat(r'D:\pt-ct-em_ansi')    #文件夹目录
    print "ALL FILES DONE!"


注: 转载请注明出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值