VScode 脚本实现GB2312转UTF8

VScode 脚本实现GB2312转UTF8

  1. 第一步
    pip install chardet,安装对应的python库
  2. 第二步
    运行代码,python convert_encoding.py
    代码如下,文件命名为convert_encoding.py

以下代码全部由chatGTP生成,从出现想法到运行代码验证效果,全过程5分钟

import os
import chardet

def detect_encoding(file_path):
    with open(file_path, 'rb') as file:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        return result['encoding']

def convert_to_utf8(file_path):
    with open(file_path, 'rb') as file:
        raw_data = file.read()
        encoding = chardet.detect(raw_data)['encoding']
        
        if encoding == 'GB2312':
            try:
                text = raw_data.decode('GB2312')
                with open(file_path, 'w', encoding='utf-8') as utf8_file:
                    utf8_file.write(text)
                print(f"Converted {file_path} to UTF-8")
            except Exception as e:
                print(f"Error converting {file_path}: {e}")

def scan_and_convert(folder_path):
    for root, dirs, files in os.walk(folder_path):
        for file in files:
            file_path = os.path.join(root, file)
            encoding = detect_encoding(file_path)
            if encoding == 'GB2312':
                convert_to_utf8(file_path)

if __name__ == "__main__":
    folder_path = input("Enter the folder path to scan: ")
    scan_and_convert(folder_path)

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值