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