批量文件编码转换用python实现的utf8转gb2312,vscode设置特殊文件的默认打开编码

批量文件编码转换用python实现的utf8转gb2312, 任意编码之间的相互转换都是可以的.改一下下面的参数即可

convert.py文件内容如下

import os
import glob
import chardet
 
#检测文件编码类型
def detect_file_encoding(file_path):
    with open(file_path, 'rb') as f:
        data = f.read()
        result = chardet.detect(data)
        encoding = result['encoding']
        confidence = result['confidence']
    return encoding, confidence
  
  
def convert_encoding(file_path, from_encoding='utf-8', to_encoding='gb2312'):  
    """  
    将文件的编码从一种转换为另一种。  
      
    :param file_path: 文件的路径  
    :param from_encoding: 原始编码  
    :param to_encoding: 目标编码  
    """  
    try:  
        #判断文件内容的编码类型,如果与to_encoding相同则不转换
        det_encoding, confidence=detect_file_encoding(file_path) 
        
        if(det_encoding == to_encoding):
            print(f"{file_path} is already in {to_encoding} encoding")
            return
        
        # 读取文件内容  
        with open(file_path, 'r', encoding=from_encoding) as file:  
            content = file.read()  
        
        # 写入文件内容到新文件(先写入临时文件,然后替换原文件)  
        temp_file_path = file_path + '.tmp'  
        with open(temp_file_path, 'w', encoding=to_encoding, errors='ignore') as file:  
            file.write(content)  
          
        # 替换原文件  
        os.remove(file_path)  
        os.rename(temp_file_path, file_path)  
        print(f"Converted {file_path} from {from_encoding} to {to_encoding}")  
    except Exception as e:  
        print(f"Failed to convert {file_path}: {e}")  
  
 
  
if __name__ == "__main__":  
    
    file_or_folder_to_convert = 'G:/demo/src/gb3l/'  # 修改为你的文件夹路径或文件路径  
    from_encoding='utf-8'
    to_encoding  ='gb2312'
    file_extensions=['.h','.c'] # 修改为你需要转换的文件类型
    #判断是文件还是文件夹
    if os.path.isfile(file_or_folder_to_convert): 
        #转换单个文件
        convert_encoding(file_or_folder_to_convert)  
    else:
        #转换文件夹下所有文件
        for root, dirs, files in os.walk(file_or_folder_to_convert):  
            for file in files:  
                #取文件扩展名
                file_extension = os.path.splitext(file)[1]
                if (file_extension in file_extensions):  
                    file_path = os.path.join(root, file)   
                    convert_encoding(file_path)

使用的时候只需要修改 代码中的这几个参数即可.

    file_or_folder_to_convert = 'G:/demo/src/gb3l/'  # 修改为你的文件夹路径  
    from_encoding='utf-8'
    to_encoding  ='gb2312'
    file_extensions=['.h','.c'] # 修改为你需要转换的文件类型

使用前需要安装python 3.8以上.
然后使用下面的命令安装chardet 库

	$> pip install chardet 

使用方法, 如下

	$> python convert.py

参数路径什么的, 直接在代码中改.这么简单的代码,是个程序员就会改. 主打一个简单易用.

vscode中指定某种类型的文件打开时的编码格式

按住ctrl+, 在弹出的设置中, 点击右上角的 这个打开json设置图标.
在这里插入图片描述
我的配置如下, .c和.h, 还有.v文件都改成了gb2312编码.

{
    "git.openRepositoryInParentFolders": "never",
    "Codegeex.Privacy": true,
    "EIDE.ARM.INI.Path": "d:\\Keil_v5\\UV4\\UV4.exe",
    "terminal.integrated.scrollback": 3000,
    "workbench.editorAssociations": {
        "*.c": "default"
    },
    "Codegeex.Comment.LanguagePreference": "中文",
    "files.associations": {
        "*.v": "verilog",
        "*.c": "c",
        "*.h": "c"
    },
    "[c]": { 
            "files.encoding": "gb2312" //设置c文件编码
    },
    "[verilog]": { 
            "files.encoding": "gb2312" //设置verilog文件编码
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值