更新:2020-03-19
最新在win10平臺用QT開發的時候發現UTF-8編碼分UTF-8 和 UTF-8 BOM兩種。UTF-8文件中放置BOM主要是微軟的習慣,但是放在別的系統上會出現問題,不含BOM的UTF-8纔是標準形式。因爲經常要跨平臺移植代碼,所以windows下寫的代碼使用utf-8保存,會自動帶上bom,移植到ubuntu下中文部分可能會亂碼。所以把編碼轉換工具擴展了下功能。
新增功能:
- 支持批量轉換任意格式的文件編碼;
- 可將文件編碼轉爲UTF-8 BOM 、UTF-8、GB2312中的任意一種格式;
github下載地址:
https://github.com/clorymmk/CodeTransmit
新版程序運行效果圖:
/**********************************以下內容爲舊版程序*********************************************/
由於本人習慣使用 MDK + VScode 進行單片機程序開發,有時候會遇到一個這樣的問題,MDK中默認的文件編碼是GB2312或ASCII,而VScode中默認的文件編碼是utf-8,其他同事有的是用MDK開發,寫的中文註釋就會變成GB2312編碼,而我這邊使用utf-8編碼打開代碼就會出現亂碼現象,每次都要重新轉換文件編碼是件麻煩的事,因此寫了個python腳本,批量轉換工程文件編碼爲utf-8。
python編碼轉換腳本:
# 編碼轉換工具,將路徑下所有".c .h .cpp .hpp .java"文件都轉爲 utf-8 格式
#i!/usr/bin/env python3
# -*- coding:utf-8 -*-
import os
import sys
import codecs
import chardet
gErrArray = []
def convert(fileName, filePath,out_enc="utf-8"):
try:
content=codecs.open(filePath,'rb').read()
source_encoding=chardet.detect(content)['encoding']
# print ("fileName:%s \tfileEncoding:%s" %(fileName, source_encoding))
print("{0:50}{1}".format(fileName, source_encoding))
if source_encoding != None:
if source_encoding == out_enc:
return
content=content.decode(source_encoding).encode(out_enc)
codecs.open(filePath,'wb').write(content)
else :
gErrArray.append("can not recgonize file encoding %s" % filePath)
except Exception as err:
gErrArray.append("%s:%s"%(filePath, err))
def explore(dir):
print("\r\n===============================================================")
print("{0:50}{1}".format('fileName', 'fileEncoding'))
print("===============================================================")
for root,dirs,files in os.walk(dir):
for file in files:
suffix = os.path.splitext(file)[1]
if suffix == '.h' or suffix == '.c' or suffix == '.cpp' or suffix == '.hpp' or suffix == '.bat' or suffix == '.java':
path=os.path.join(root,file)
convert(file, path)
def main():
#explore(os.getcwd())
filePath = input("請輸入要轉換編碼的文件夾路徑: \n")
explore(filePath)
print('\r\n---------錯誤統計------------')
for index,item in enumerate(gErrArray):
print(item)
print('\r\n 共%d個錯誤!'%(len(gErrArray)))
if(len(gErrArray) > 0):
print("出現錯誤時,可手動找到錯誤文件,用notepad++打開後,點擊編碼,改爲utf-8保存")
print('\r\n-----------------------------')
if __name__=="__main__":
while True:
main()
input("\r\n########### 按回車鍵繼續轉換!!! ###########\r\n")
該程序支持.c .h .cpp .hpp .bat .java等6種格式的文件編碼轉換,如果需要添加其他格式的文件,直接修改suffix的條件判斷處的語句即可。
附上windows平臺下的可執行程序下載鏈接:(壓縮包中帶有源碼和exe程序,如需在linux平臺下運行,由於linux默認自帶python, pip3安裝chardet庫後,即可運行源碼)