KEIL 中文乱码 非UTF格式文件批量修改

概要

在用Keil 环境编写程序过程中或引用第三方程序时会出现的中文乱码现象,经查找需要.在editor的选项卡里面encoding把编码改为chinese gb2312或utf-8,但已经存在的.C .H文件编码的修改就需要采用另存方式一个一个手动修改,当项目中文件众多或多个项目时就很麻烦,于是就用了下面的代码来批量修改。

方法流程

1、首先将edit–>configration–>editer里面的Encoding修改为Encode in UTF-8 without signature
在这里插入图片描述
2、将下面代码拷贝存为.py格式。
import os
import chardet
import PySimpleGUI as sg;

def detect_file_encoding(file_path):
“”"
检测文件的编码
:param file_path: 文件路径
:return: 检测到的编码
“”"
with open(file_path, ‘rb’) as f:
raw_data = f.read()
result = chardet.detect(raw_data)
return result[‘encoding’]

def convert_file_to_utf8(file_path):
“”"
将单个文件转换为 UTF-8 编码
:param file_path: 文件路径
“”"
try:
# 检测文件编码
original_encoding = detect_file_encoding(file_path)
if not original_encoding:
print(f"无法检测编码: {file_path}")
return

    # 读取文件内容(使用检测到的编码)
    with open(file_path, 'r', encoding=original_encoding) as f:
        content = f.read()
    
    # 将内容写入文件(使用 UTF-8 编码)
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    
    print(f"转换成功: {file_path} (原始编码: {original_encoding})")
except Exception as e:
    print(f"转换失败: {file_path} - 错误: {e}")

def batch_convert_to_utf8(directory, extensions):
“”"
批量转换文件夹中指定后缀的文件为 UTF-8 编码
:param directory: 文件夹路径
:param extensions: 需要处理的文件后缀列表(如 [‘.txt’, ‘.csv’])
“”"
for root, dirs, files in os.walk(directory):
for file in files:
# 检查文件后缀
if any(file.endswith(ext) for ext in extensions):
file_path = os.path.join(root, file)
convert_file_to_utf8(file_path)

if name == “main”:

answer = sg.popup_yes_no("确定要转换吗?")
if answer != "Yes":
    raise SystemExit("退出")
# 设置文件夹路径和需要处理的后缀
extensions = [".c", ".h", ".V"]  # 替换为需要处理的后缀列表[".v""]

# 窗口显示文本框和浏览按钮, 以便选择一个文件夹
folder_path = sg.popup_get_folder("Select Folder")
if not folder_path:
    # sg.popup("Cancel", "No folder selected")
    raise SystemExit("Cancelling: no folder selected")
    
else:
    # 调用批量转换函数
    batch_convert_to_utf8(folder_path, extensions)
    sg.popup("转换完成") 

3、运行(点击保存路径,输入cmd回车打开代码窗口,接着输入python A.py(注意!!!这里的A.py是你保存的文件名))
输入要修改文件夹中
在这里插入图片描述

小结

` 注意仅在公司几台WIN10系统下测试通过。在批量测试中发现偶尔有几个文件显示转换成功但打开后发现还是原格式。如果嫌弃麻烦我写好了一个.exe文件可以直接下载。https://download.youkuaiyun.com/download/SSS3SUN/90675724?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522cba02e01d834fb8a6662865ae235571b%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fdownload.%2522%257D&request_id=cba02e01d834fb8a6662865ae235571b&biz_id=1&utm_medium=distribute.pc_search_result.none-task-download-2downloadfirst_rank_ecpm_v1~times_rank-1-90675724-null-null.269v2control&utm_term=keil%20%E4%B9%B1%E7%A0%81&spm=1018.2226.3001.4451.1

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值