使用python改变文件夹中的代码文件编码

2017-1-18 python

现状:

项目以前在windows底下写的使用的编码是gbk

在mac os底下用xcode显示中文乱码

解决方式:

    把项目底下文件的编码改为utf-8编码

使用工具:

    python

代码如下:

   

#-*- coding:utf-8 -*-

import os

class CodeConvert :

    def __init__(self, path, dcode, scode) :

        self.file_lists = []

        if os.path.exists(path) :

            self.parent_path = path

        else :

            self.parent_path = ""

        self.dest_code = dcode

        self.src_code = scode

        self.exts = [".cpp", ".c", ".h"]

    def ListFiles(self) :

        for root, dirs, files in os.walk(self.parent_path) :

            for name in files :

                self.file_lists.append(os.path.join(root, name))

    def Convert2DestCode(self) :

        for file in self.file_lists:

            ext = os.path.splitext(file)[1]

            ext = ext.lower()

            if ext in self.exts :

                self.Convert(file)

    def Convert(self, file) :

        try :

            print file

            f = open(file)

            buf = f.read()

            f.close()

            u1 = buf.decode(self.src_code)

            utf1 = u1.encode(self.dest_code)

            f = open(file, 'w+')

            f.write(utf1)

            f.close()

        except :

            print "except" + file


def main() :

    convert = CodeConvert('/Users/xxx/Desktop/xxx', 'utf8', 'gbk')

    convert.ListFiles()

    convert.Convert2DestCode()

标签: python utf8 gbk xcode

评论(0) 浏览(2459)

Powered by EMLOG Copyright @ 深圳市炽旗科技 版权所有. 闽ICP备14012694号-2