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

断了今生、忘了曾经 提交于 2019-12-26 12:00:14

简单实现.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)

  

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!