Python修改文件编码为UTF-8-SIG

前言:平时在开发过程中避免不了在windows环境和liunx环境下同时编译代码,由于windows和liunx环境下编码默认是不一致,从而导致VS编译中报一些奇怪的错误,当然您也可以通过设置Git,来避免这种情况,这里提供一个python脚本用于批量将文件格式转换为:UTF-8-SIG
# -*- coding: UTF-8 -*-
import codecs
import os
import chardet

contenttypes = [".c", ".cpp", ".h", ".hpp"]

def convert_encoding(filename, target_encoding):
    # 将文件从源编码转换为目标编码

    # 以只读方式打开文件(r), 二进制文件(b), 打开一个文件进行更新(可读可写 +)
    content = codecs.open(filename, 'rb+').read()
    # 识别打开文件的编码
    source_encoding = chardet.detect(content)['encoding']
    # 获取文件内的内容
    content = content.decode(source_encoding, 'ignore')
    # 以 UTF-8-SIG 的方式将文件保存
    codecs.open(filename, 'w', encoding=target_encoding).write(content)

def main():
    for root, dirs, files in os.walk("."):
        for name in files:
            for fifotype in contenttypes:
                # 如果字符串含有指定的后缀返回True,否则返回False
                if name.lower().endswith(fifotype):
                    # Path20 = home\develop\code
                    filename = os.path.join(root, name)
                    print(filename)
                    convert_encoding(filename, 'UTF-8-SIG')

if __name__ == '__main__':
    main()
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容