当前位置: 首页 > article >正文

批量文件编码转换用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文件编码
    }
}

http://www.kler.cn/news/293592.html

相关文章:

  • 数据赋能(198)——开发:数据应用——技术方法、主要工具
  • DAY69
  • vue , 微信小程序 , uni-app绑定变量属性
  • 【2024】MySQL库表基本操作
  • 算法:图片压缩算法【Z字行扫描】(Java实现)
  • 相亲交友系统商业开发
  • 【最新华为OD机试E卷-支持在线评测】分糖果(100分)-多语言题解-(Python/C/JavaScript/Java/Cpp)
  • 用ACF和PACF计算出一堆数据的周期个数以及周期时长,数据分析python
  • Linux系统练习笔记【完整版】
  • .NET/C#⾯试题汇总系列:⾯向对象
  • SpringBoot整合openApi
  • 数据分析的革命:Docker容器化在数据分析中的应用
  • ssm微信小程序校园失物招领论文源码调试讲解
  • 【HTML】置换元素(替换元素)
  • 什么是区块链?
  • vue3+ts项目import导入路径用@/报错找不到模块“@/components/也没有快捷提示
  • 小米红米系列机型 机型代码查询总目录 adb指令查询步骤
  • 【论文精读】SCINet-基于降采样和交互学习的时序卷积模型
  • 2024国赛数学建模ABC题思路模型
  • 软件测试学习笔记丨Pytest的使用
  • 【Pytorch实用教程】【分布式】torch.distributed.all_reduce用法详细介绍
  • 【.NET全栈】ASP.NET开发Web应用——LINQ技术
  • CentOS7.9下安装snmp
  • 目标检测-YOLOv6
  • Lenze伦茨E82ZBC, E82ZBB E82ZMBRB安装说明手测
  • 1-10 图像增强对比度 opencv树莓派4B 入门系列笔记
  • Swift知识点---RxSwift学习
  • Centos配置双网卡绑定(bond)
  • Apache Tomcat 6.0.45 下载、安装和配置教程
  • YOLO缺陷检测学习笔记(3)