python修改文件编码为utf-8格式


简单实现.h,.c文件修改编码为utf-8格式。

import os;
import chardet;

file_path = ".";

for root,dirs,files in os.walk(file_path):
    # print("root",root)
    # print("files",files)
    for fn in files:
        if fn[-2:] == '.h' or fn[-2:] == '.c':
            bak = fn + "_bak"
            f1 = open(root + "\\" + fn,"rb")

            data = f1.read()
            encode = chardet.detect(data).get('encoding')
            f1.close()
            fn = root + "\\" + fn
            bak = root + "\\" + bak
            if encode == "utf-8":
                print(fn,"is utf-8 encoding")
                continue;
            with open(fn,"r",encoding=encode) as f1 ,open(bak,"w",encoding="utf-8") as f2:
                for line in f1:
                    f2.write(line)
            os.remove(fn)
            os.rename(bak,fn)

  


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM