c++右键菜单统一转化文件为utf8编码

reg文件如图,注册右键菜单

剩下的自己捣鼓吧

powershell 复制代码
Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\code_tran]
"icon"="C:\\using_software\\code_tran_software\\fff.ico"
@="gbk转utf8"

[HKEY_CLASSES_ROOT\Directory\shell\code_tran\command]
@="C:\\using_software\\code_tran_software\\2067_gbk_to_utf8.exe \"%1\""
python 复制代码
import traceback
import os
import shutil
import sys


import os

def get_path_list(file_path):
    directory = os.path.dirname(file_path)
    filename = os.path.basename(file_path)
    file_name, file_extension = os.path.splitext(filename)
    return directory, file_name, file_extension



def get_all_file(path):
    # import os
    return_list=[]
    for root,dirs,files in os.walk(path,topdown=True):
        for file_one in files:
            use_path=root+'/'+file_one
            return_list.append(use_path.replace('/','\\'))
    return return_list

def del_file(path):
    #!/usr/bin/env python
    import os
    import shutil
    filelist=[]
    rootdir=path
    filelist=os.listdir(rootdir)
    for f in filelist:
      filepath = os.path.join( rootdir, f )
      if os.path.isfile(filepath):
        os.remove(filepath)
        #print filepath+" removed!"
      elif os.path.isdir(filepath):
        shutil.rmtree(filepath,True)
        #print "dir "+filepath+" removed!"


def make_file(path):
    try:
        os.makedirs(path)
    except:
        pass

# def get_all_txt(txt_path):
#     return_list=[]
#     lines  = open(txt_path,'r',encoding='utf8',errors='ignore')
#     for line in lines:
#         # print(line)
#         # line=line.replace(' ','')
#         line=line.replace('\n','')
#         return_list.append(line)
#         # if 'def ' in line and '(' in line and ')' in line:
#         #     return_list.append(str(line))

#         # return_list.append(int(line))
#     lines.close()
#     return return_list

import os

#  获得打包以后得路径。
def get_exe_path(relative_path=''):
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return os.path.join(os.path.abspath("."), relative_path)[:-1]

def get_year_month_day_number():
    import datetime
    year=str(int(datetime.datetime.now().year))
    month=str(int(datetime.datetime.now().month))
    day=str(int(datetime.datetime.now().day))
    return year+'-'+month+'-'+day

import xlsxwriter
def write_xlsx_list(path,write_list):
    workbook_zheng = xlsxwriter.Workbook(path)     #新建excel表
    worksheet_zheng = workbook_zheng.add_worksheet('sheet1')       #新建sheet(sheet的名称为"sheet1")
    # worksheet_zheng.set_column(0,1,50)
    # worksheet_zheng.set_column(1,2,20)
    # worksheet_zheng.set_column(2,10,50)
    for fx in range(0,len(write_list)):
        try:
            x_list=write_list[fx]
            for fy in range(0,len(x_list)):
                y_v=x_list[fy]
                worksheet_zheng.write(fx,fy,y_v)
            # print(x_list)
        except:
            pass
    workbook_zheng.close()

def ocr_func_list():
    # from ocr_system import *
    ocr = GetOcrApi()
    png_json = get_png_json(read_one) # 输入图片,返回jso格式得结果
    get_ocr_png_list(pdfPath, imagePath,num=1)
    read_file_to_json()
    write_json_to_file()
    ocr_show(png_json)
    ocr.close()
    pass

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------
def get_xlsx_list(xlsx_path,sign=0):
    import xlrd
    read_one=xlsx_path
    match_write_in_fp=xlrd.open_workbook(xlsx_path)
    sheet_names_list = match_write_in_fp.sheet_names()
    sh_read=match_write_in_fp.sheet_by_name(sheet_names_list[0])  #根据sheet索引获得第一个sheet。
    # print(sh_read.row_values(0))
    sum_list=[]
    for line_number in range(sign,sh_read.nrows):
        try:
            alone_line=sh_read.row_values(line_number)
            sum_list.append(alone_line)
        except:
            pass
    return sum_list





# 数据ok了,开始写
def write_xlsx_dict_list(path,write_list_2):
    workbook_zheng = xlsxwriter.Workbook(path)     #新建excel表
    worksheet_zheng = workbook_zheng.add_worksheet('Lead')       #新建sheet(sheet的名称为"sheet1")
    # worksheet_zheng.set_column(0,1,50)
    write_list= write_list_2[0]
    for fx in range(0,len(write_list)):
        try:
            x_list=write_list[fx]

            red_font = workbook_zheng.add_format(x_list[1])
            # print(x_list[1])
            for fy in range(0,len(x_list[0])):
                y_v=x_list[0][fy]
                y_v= str(y_v)
                if y_v[-2:]=='.0':
                    y_v=y_v[:-2]
                worksheet_zheng.write(fx,fy,y_v,red_font)
            # print(x_list)
        except Exception as e:
            pass
            # print(e)
    worksheet_zheng = workbook_zheng.add_worksheet('更多信息')       #新建sheet(sheet的名称为"sheet1")
    # worksheet_zheng.set_column(0,1,50)
    write_list=write_list_2[1]
    for fx in range(0,len(write_list)):
        try:
            x_list=write_list[fx]

            red_font = workbook_zheng.add_format(x_list[1])
            # print(x_list[1])
            for fy in range(0,len(x_list[0])):
                y_v=x_list[0][fy]
                y_v= str(y_v)
                if y_v[-2:]=='.0':
                    y_v=y_v[:-2]
                worksheet_zheng.write(fx,fy,y_v,red_font)
            # print(x_list)
        except Exception as e:
            pass
            # print(e)

    workbook_zheng.close()




def get_current_time():
    from datetime import datetime
    now = datetime.now()
    return str(now.strftime("%Y_%m_%d %H_%M_%S"))



import json
def read_file_to_json(file_path):
    with open(file_path, 'r', encoding='utf-8') as file:
        try:
            json_data = json.load(file)
        except UnicodeDecodeError:
            file.seek(0)
            json_data = json.load(file, encoding='gbk')
    return json_data

import json

def write_json_to_file(file_path, data_list):
    with open(file_path, 'w', encoding='utf-8') as file:
        json.dump(data_list, file, ensure_ascii=False, indent=4)



import pickle
def write_dict_to_file(dict_obj, file_path):
    with open(file_path, 'wb') as file:
        pickle.dump(dict_obj, file)

def read_dict_from_file(file_path):
    with open(file_path, 'rb') as file:
        dict_obj = pickle.load(file)
    return dict_obj



def json_to_string(data):
    """
    将JSON对象转换为字符串
    """
    return json.dumps(data)

def string_to_json(string):
    """
    将字符串转换为JSON对象
    """
    # print('str  ',string    )
    return json.loads(string)




def extract_numbers2(string):
    numbers = re.findall(r'\d+', string)
    return [int(num) for num in numbers]



def num_col(number):
    number=number+1
    column = ""
    while number > 0:
        number -= 1
        column = chr(number % 26 + 65) + column
        number //= 26
    return column

def col_num(column):
    column=str(column).upper()
    number = 0
    for i in range(len(column)):
        number = number * 26 + ord(column[i]) - 64
    return number - 1



def move_file(p1,p2):
    xx= p1.replace('\\','/').split('/')[-1]
    ss= p2+'/'+xx
    make_file(ss)
    for x in get_all_file(p1):
        shutil.copy(x,ss)






import copy
def fill_list_fuc(lst,mlen):
    lst =copy.deepcopy(lst)
    # 如果列表长度小于6,则在列表末尾添加空字符串,直到长度为6
    while len(lst) < mlen:
        lst.append("")
    return lst

def split_list_fuc(l, n=2):
    """
    把一个list切分为n份,返回n个list
    :param l: 要切分的列表
    :param n: 切分的份数
    :return: 切分后的列表
    """
    if l is None or n < 1:
        return []

    if n >= len(l):
        return [l[i:i+1] for i in range(len(l))]

    return [l[i:i + len(l)//n + 1] for i in range(0, len(l), len(l)//n + 1)]



import   copy
import random


# 给定一个list,打乱顺序
def shuffle_list_fuc(data_list):
    re_list = data_list.copy()
    for i in range(len(re_list)-1, 0, -1):
        j = random.randint(0, i)
        re_list[i], re_list[j] = re_list[j], re_list[i]
    return re_list




import datetime


class TimeLogger:
    def __init__(self):
        import datetime
        self.start_time = datetime.datetime.now()
        self.previous_time = self.start_time
        self.time_log = []
        self.time_number = 0

    def get_now_time(self,show_str = ''):
        current_time = datetime.datetime.now()
        time_diff = current_time - self.previous_time
        self.previous_time = current_time
        self.time_log.append((current_time, time_diff))

        current_time_str = current_time.strftime("%Y-%m-%d %H:%M:%S.%f")
        time_diff_str = str(time_diff)
        # time_log,append()
        if str(show_str)=='':
            print(["时间差值: ",self.time_number,time_diff_str, current_time_str])
        else:
            print(["时间差值: ",self.time_number,time_diff_str, current_time_str,show_str])
        
        self.time_number=self.time_number+1


# 示例用法
logger = TimeLogger()

logger.get_now_time()



# def get_all_txt(txt_path):
#     return_list=[]
#     lines  = open(txt_path,'r',encoding='utf8')
#     for line in lines:
#         # print(line)
#         # line=line.replace(' ','')
#         line=line.replace('\n','')
#         # if 'def ' in line and '(' in line and ')' in line:
#         #     return_list.append(str(line))
#         return_list.append(str(line))
#     lines.close()
#     return return_list

def get__txt_fuc(txt_path):
    sign = True
    txt = ""
    try:
        with open(txt_path, "r", encoding="gbk") as f:
            txt = f.read()
    except UnicodeDecodeError:
        try:
            with open(txt_path, "r", encoding="utf8") as f:
                txt = f.read()
        except UnicodeDecodeError:
            sign = False
    return sign, txt

def write_txt_fuc(txt_path, content):
    with open(txt_path, "w", encoding="utf8") as f:
        f.write(content)

# w文件区域。
main_path=os.getcwd()  # exe文件存放的路径。
exe_path=get_exe_path()  #  打包以后资源文件存放的路径。


print('操作路径  ',[sys.argv[1]])

read_path=  sys.argv[1]
# read_path = r'C:\Users\Admin\Desktop\1\bpNet_test'



read_path= read_path.replace('\\','/')
write_path =  '/'.join(read_path.split('/')[:-1])
write_new_path= write_path+'/'+read_path.split('/')[-1]+'_utf8'

make_file(write_new_path)

del_file_list = get_all_file(write_new_path)

import os  
import glob  
import sys
  
def remove_empty_folders(directory):  
    # 遍历指定目录下的所有文件和子目录  
    # del_file(directory)
    for filename in glob.glob(f'{directory}/**', recursive=True):  
        # 检查是否是文件夹  
        if os.path.isdir(filename):  
            # 如果是空的文件夹,就删除它  
            if not os.listdir(filename):  
                os.rmdir(filename)  
                print(f'删除空文件夹: {filename}')
    # os.rmdir(filename) 
    # os.rmdir(directory)  
  
# 设置递归调用深度,默认为1000
sys.setrecursionlimit(10**5)
# 使用方法,更换为自己的目录  
# remove_empty_folders('G:\\123\\')


import os  
import glob  
import sys
  
def get_all_path_fuc(path):
    re_list = [ ]
    for filename in glob.glob(f'{path}/**', recursive=True):  
        # 检查是否是文件夹  
        if os.path.isdir(filename):  
            re_list.append(filename)
    
    return re_list[1:]





print('写入文件夹 ',write_new_path)
if len(del_file_list)>=1:

    del_path_list = get_all_path_fuc(write_new_path)

    pp_path = write_new_path+f'/{get_current_time()}'
    # make_file(pp_path )
    for file_one in del_file_list:
        try:    
            pps_list = get_path_list(file_one)
            # print(pps_list)
            # 开始复制过来
            new_file_one = file_one.replace('\\','/').replace(write_new_path.replace('\\','/'),pp_path)
            
            # print(new_file_one)
            pp_list = get_path_list(new_file_one)
            make_file(pp_list[0])
            os.rename(file_one,new_file_one)
            # if 1==1:
            # try:
            # if pps_list[0].replace('\\','/') != write_new_path:
            #     remove_empty_folders(pps_list[0])
            # except:
            #     pass
        except:
            pass

    for one in  del_path_list:
        # print('del_file ',[one])
        if '/'.join(one.replace('\\','/').split('/')[:-1]) == write_new_path.replace('\\','/'):
            one = one.replace('/','\\')
            try:
                del_file(one)
                os.rmdir(one) 
            except Exception as e:
                pass
                print('error ',[one],e)
                # break
    remove_empty_folders(write_new_path)

    # del_file(write_new_path)


read_path_list=get_all_file(read_path)
main_len = len(read_path_list)
for mi,file_one in enumerate(read_path_list):
    try:
        if (mi+1)%10==0:
            print(f'进度 {mi+1}/{main_len}')
        new_file_one = file_one.replace('\\','/').replace(read_path,write_new_path)
        pp_list = get_path_list(new_file_one)
        make_file(pp_list[0])
        re_list = get__txt_fuc(file_one)
        # print([re_list[0],new_file_one,file_one])
        if re_list[0]==True:
            write_txt_fuc(new_file_one,re_list[1])
        else:
            shutil.copy(file_one,new_file_one)
    except:
        traceback.print_exc()
        pass

print(f'进度 {mi+1}/{main_len}')

print('处理完毕 ',f'{read_path } to { write_new_path } --->{main_len}个')

logger.get_now_time('end')

os.system("pause")
复制代码
相关推荐
点云SLAM1 小时前
C++包装器之类型擦除(Type Erasure)包装器之小对象优化(SBO, Small Buffer Optimization)示例(5)
c++·内存管理·c++高级应用·c++包装器·类型擦除包装器·内存小对象优化
伐尘1 小时前
【MySQL】windows系统下mysql慢日志查询
windows·mysql·adb
ZAz_1 小时前
DAY 28 元组和OS模块
python
curry____3031 小时前
study in PTA(高精度算法与预处理)(2025.12.3)
数据结构·c++·算法·高精度算法
私人珍藏库1 小时前
[Windows] 隐写者 SteganographierGUI 1.3.8
windows·pc·工具·软件
plmm烟酒僧1 小时前
OpenVINO 推理 YOLO Demo 分享 (Python)
图像处理·人工智能·python·yolo·openvino·runtime·推理
星云数灵1 小时前
机器学习入门实战:使用Scikit-learn完成鸢尾花分类
人工智能·python·机器学习·ai·数据分析·pandas·python数据分析
weixin_387002151 小时前
二次开发的openssl在windows平台的编译
linux·windows·安全·ssl
JustNow_Man1 小时前
【UV】 推荐使用UV管理Python
人工智能·python·uv