前言:平时在开发过程中避免不了在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()