python 轉化文件編碼 utf8


使用visual studio最大的一個問題就是文件編碼問題,當文件中有中文時,visual studio 會默認為區域編碼,也就是gb2312,如果想跨平台或者不用vs編譯的話,就會因為編碼問題導致各種錯誤。

所以寫了個python腳本來檢測原文件編碼並轉換為目標編碼,以下代碼以目標編碼為utf-8為例:

需要安裝chardet,詳情:https://pypi.python.org/pypi/chardet 

使用方法:python to_utf8.py /my_project/src

import codecs
import os
import sys
import shutil
import re
import chardet

convertdir = sys.argv[1]
convertfiletypes = [
  ".cpp",
  ".h",
  ".hpp"
  ]

def convert_encoding(filename, target_encoding):
    # Backup the origin file.

    # convert file from the source encoding to target encoding
    content = codecs.open(filename, 'r').read()
    source_encoding = chardet.detect(content)['encoding']
    if source_encoding != 'utf-8':
        print source_encoding, filename
        content = content.decode(source_encoding, 'ignore') #.encode(source_encoding)
        codecs.open(filename, 'w', encoding=target_encoding).write(content)

def main():
    for root, dirs, files in os.walk(convertdir):
        for f in files:
            for filetype in convertfiletypes:
                if f.lower().endswith(filetype):
                    filename = os.path.join(root, f)
                    try:
                        convert_encoding(filename, 'utf-8')
                    except Exception, e:
                        print filename

if __name__ == '__main__':
    main()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM