Python更改文件的编码格式

Python更改文件的编码格式



import os
from chardet.universaldetector import UniversalDetector

def change_encode(file,change_2_type):
    def get_encode_info(file):
        """
        读取文件的编码方式
        """
        with open(file, 'rb') as f:
            detector = UniversalDetector()
            for line in f.readlines():
                detector.feed(line)
                if detector.done:
                    break
            detector.close()
            return detector.result['encoding']


    def read_file(file):
        with open(file, 'rb') as f:
            return f.read()

    def convert_encode2_youwant(file, original_encode, des_encode):
        """
        将文件编码成你想要的格式
        :param file:
        :param original_encode:
        :param des_encode:
        :return:
        """
        file_content = read_file(file)
        file_decode = file_content.decode(original_encode, 'ignore')
        file_encode = file_decode.encode(des_encode)
        with open(file, 'wb') as f:
            f.write(file_encode)

    real_type=get_encode_info(file)
    if real_type!=change_2_type:
        """
            判断你想要的和实际编码是否相同 判断是否需要变更
        """
        convert_encode2_youwant(file,real_type,change_2_type)

    now_type= get_encode_info(file)
    if now_type==change_2_type:
        #判断是否成功
        return True
    else:
        return False
if __name__=="__main__":
    flag=change_encode("分公司箱型箱量(1).csv","utf-8")
    print(flag)



你可能感兴趣的:(python,开发语言,算法,pip)