吾爱破解 - LCG - LSG |安卓破解|病毒分析|www.52pojie.cn

 找回密码
 注册[Register]

QQ登录

只需一步,快速开始

查看: 1797|回复: 23
收起左侧

[原创工具] 针对文件被更改后缀,用py写了个恢复文件原始的后缀的小工具!

  [复制链接]
141442478 发表于 2023-8-23 23:04
头一回使用用py写带界面的工具,
献丑了各位!
还打包成 exe 了, 可以直接使用!
[Python] 纯文本查看 复制代码
import os
import shutil
from tkinter import messagebox, filedialog, Frame, StringVar, Label, Entry, Button, Tk
import filetype


def count_w_h_x_y(main_root):
    # 获取当前屏幕的宽度和高度
    screen_width = main_root.winfo_screenwidth()
    screen_height = main_root.winfo_screenheight()

    _width = int(screen_width * 2.8 / 10)
    _height = int(screen_height * 3 / 10)
    _float_x = int((screen_width - _width) / 2)
    _float_y = int((screen_height - _height) / 2)

    return _width, _height, _float_x, _float_y


class TkApplication(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.root_path = StringVar()
        self.open_path = ''
        self.master = master
        self.create_widget()

    def create_widget(self):
        """
        原文件支持类型:
        image:jpg,png,gif,web,cr2,tif,bmp,jxr,psd,ico
        video:mp4,m4v,mkv,web,mov,avi,wmv,mpg,flv
        audio:mid,mp3,m4a,ogg,flac,wav,amr
        application: epub,zip,tar,rar,gz,bz2,7z,xz,pdf,exe,swf,rtf,eot,ps,sqlite,nes,crx,cab,deb,ar,Z,lz
        font: woff,woff2,ttf,otf
        """
        Label(root, text='选择文件夹: ', font=('华文彩云', 15)).place(x=50, y=80, height=30)
        Entry(root, textvariable=self.root_path, font=('FangSong', 10), width=30, state='readonly').place(x=170, y=80,
                                                                                                          height=30)
        Button(root, text='选择路径', command=self.get_path).place(x=400, y=80, height=30)
        Button(root, text='确定(开始执行)', font=('华文彩云', 15), command=self.deal_fix_img).place(x=50, y=150, width=410)

    def get_path(self):
        # 返回一个字符串,可以获取到任意文件的路径。
        path1 = filedialog.askdirectory(title='请选择文件')
        self.root_path.set(path1)

    def deal_fix_img(self):
        # dir_str = r'C:\Users\Administrator\Pictures\fix_img'
        dir_str = self.root_path.get()
        if not dir_str:
            # 请选择路径
            messagebox.showwarning('警告!', '请选择路径!')
            return

        fix_success_dir = f"{dir_str}/fix_success_dir"
        if not os.path.exists(fix_success_dir):
            os.makedirs(fix_success_dir)

        if not os.listdir(dir_str):
            messagebox.showwarning('警告!', '所选文件夹下无文件!')
            return
        for file in os.listdir(dir_str):
            abs_file_path = f"{dir_str}/{file}"
            if os.path.isdir(abs_file_path):
                continue
            try:
                kind = filetype.guess(abs_file_path)
                if kind is None:
                    continue
                file_type = kind.extension
            except Exception as e:
                continue
            old_file_name, old_file_type = os.path.splitext(file)
            if old_file_type.lower() == f'.{file_type}' or not file_type:
                continue

            new_img = f"{fix_success_dir}/{old_file_name}.{file_type}"
            shutil.copy2(abs_file_path, new_img)

        messagebox.showinfo('OK!', '处理完成')
        self.open_path = fix_success_dir

        Button(root, text='打开处理文件夹!', font=('华文彩云', 15), command=self.open).place(x=50, y=190, width=410)

    def open(self):
        os.system(f"start {self.open_path}")


if __name__ == '__main__':
    root = Tk()
    root.title('批量修复文件原始格式!')
    width, height, float_x, float_y = count_w_h_x_y(root)
    root.geometry(f'{width}x{height}+{float_x}+{float_y}')  # 设置窗口大小 左上角X,Y坐标
    app = TkApplication(master=root)

    root.mainloop()



度盘: 链接:https://pan.baidu.com/s/1lBnPjkZxEU1R70riBrQQmg?pwd=l8sm
提取码:l8sm
--来自百度网盘超级会员V8的分享

免费评分

参与人数 3吾爱币 +9 热心值 +3 收起 理由
ma344578245 + 1 + 1 用心讨论,共获提升!
henancappucc + 1 + 1 我很赞同!
风之暇想 + 7 + 1 感谢发布原创作品,吾爱破解论坛因你更精彩!

查看全部评分

本帖被以下淘专辑推荐:

发帖前要善用论坛搜索功能,那里可能会有你要找的答案或者已经有人发布过相同内容了,请勿重复发帖。

 楼主| 141442478 发表于 2023-8-24 10:28
少马石 发表于 2023-8-24 10:17
这个怎么识别文件原有的格式?

通过读取文件头 来匹配格式
类似这样:
b'\xff\xd8\xff': JPEG
b'\x89PNG': PNG
b'ID3': MP3
b'%PDF': PDF
 楼主| 141442478 发表于 2023-8-27 22:42
@6767 @wdlla2
听取建议 增加了后台任务 以保证处理文件时界面不被卡死,增加了拖拽功能可以处理单个或多个文件!
[Python] 纯文本查看 复制代码
import os
import shutil
from tkinter import messagebox, filedialog, Frame, StringVar, Label, Entry, Button, Tk, DISABLED, NORMAL
import filetype
import threading
import windnd


def count_w_h_x_y(main_root):
    # 获取当前屏幕的宽度和高度
    screen_width = main_root.winfo_screenwidth()
    screen_height = main_root.winfo_screenheight()
    _width = int(screen_width * 2.8 / 10)
    _height = int(screen_height * 3 / 10)
    _float_x = int((screen_width - _width) / 2)
    _float_y = int((screen_height - _height) / 2)

    return _width, _height, _float_x, _float_y


class TkApplication(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        self.enter_btn = None
        self.open_btn = None
        self.tk_th = None
        self.root_path = StringVar()
        self.new_files = StringVar()
        self.file_paths = []
        self.open_path = ''
        self.master = master
        self.create_widget()
        self.is_dir = False
        self.is_file = False

    def create_widget(self):
        """
        原文件支持类型:
        image:jpg,png,gif,web,cr2,tif,bmp,jxr,psd,ico
        video:mp4,m4v,mkv,web,mov,avi,wmv,mpg,flv
        audio:mid,mp3,m4a,ogg,flac,wav,amr
        application: epub,zip,tar,rar,gz,bz2,7z,xz,pdf,exe,swf,rtf,eot,ps,sqlite,nes,crx,cab,deb,ar,Z,lz
        font: woff,woff2,ttf,otf
        """
        Label(root, text='选择文件夹: ', font=('华文彩云', 15)).place(x=50, y=80, height=30)
        Entry(root, textvariable=self.root_path, font=('FangSong', 10), width=30, state='readonly').place(x=170, y=80,
                                                                                                          height=30)
        Label(root, text='文件: ', font=('华文彩云', 15)).place(x=50, y=120, height=30)
        Entry(root, textvariable=self.new_files, font=('FangSong', 10), width=30, state='readonly').place(x=170, y=120,
                                                                                                          height=30)
        Button(root, text='选择路径', command=self.get_path).place(x=400, y=80, height=30)
        self.enter_btn = Button(root, text='确定(开始执行)', font=('华文彩云', 15),
                                command=lambda: self.background(self.deal_fix_file))
        self.enter_btn['state'] = DISABLED
        self.enter_btn.place(x=50, y=160, width=410)

        self.open_btn = Button(root, text='打开处理文件夹!', font=('华文彩云', 15), command=self.open)
        self.open_btn['state'] = DISABLED
        self.open_btn.place(x=50, y=200, width=410)
        windnd.hook_dropfiles(self.master, func=self.dragged_files)

    def get_path(self):
        # 返回一个字符串,可以获取到任意文件的路径。
        path1 = filedialog.askdirectory(title='请选择文件')
        path1 = path1.replace('/', '\\')
        self.root_path.set(path1)
        self.file_paths = []
        self.open_btn['state'] = DISABLED
        self.enter_btn['state'] = NORMAL
        self.new_files.set('')

    def deal_fix_file(self):

        dir_str = self.root_path.get()

        if all([not dir_str, not self.file_paths]):
            # 请选择路径
            messagebox.showwarning('警告!', '请选择路径或文件!')
            return

        if all([self.is_dir, self.file_paths]):
            dir_str = (self.file_paths[0]).replace('/', '\\')

        fix_success_dir = os.path.join(dir_str, 'fix_success_dir')

        if all([self.is_file, self.file_paths]):
            _dir_str, _ = os.path.split(self.file_paths[0])
            fix_success_dir = os.path.join(_dir_str, 'fix_success_dir')

        if not os.path.exists(fix_success_dir):
            os.makedirs(fix_success_dir)

        files = self.file_paths
        if dir_str:
            if not os.listdir(dir_str):
                messagebox.showwarning('警告!', '所选文件夹下无文件!')
                return
            files = os.listdir(dir_str)

        for file in files:
            if dir_str:
                abs_file_path = os.path.join(dir_str, file)
            else:
                abs_file_path = file

            if os.path.isdir(abs_file_path):
                continue
            try:
                kind = filetype.guess(abs_file_path)
                if kind is None:
                    continue
                file_type = kind.extension
            except Exception as e:
                continue

            if not dir_str:
                _, file = os.path.split(file)

            old_file_name, old_file_type = os.path.splitext(file)
            if old_file_type.lower() == f'.{file_type}' or not file_type:
                continue

            new_file = os.path.join(fix_success_dir, f"{old_file_name}.{file_type}")
            shutil.copy2(abs_file_path, new_file)

        messagebox.showinfo('OK!', '处理完成')
        self.open_path = fix_success_dir
        self.open_btn['state'] = NORMAL
        self.enter_btn['state'] = DISABLED

    def open(self):
        os.system(f"start {self.open_path}")
        self.enter_btn['state'] = DISABLED

    def background(self, func):
        """使用线程保证处理文件时不卡顿"""
        self.tk_th = threading.Thread(target=func)
        self.tk_th.setDaemon(True)
        self.tk_th.start()

    def dragged_files(self, files):
        """拖拽获取文件路径"""
        new_files = []
        is_file = False
        is_dir = False
        for file in files:
            try:
                file = file.decode('utf-8')
            except Exception as e:
                file = file.decode('gbk')
            finally:
                new_files.append(file)
            if os.path.isdir(file):
                is_dir = True
            else:
                is_file = True

        if all([is_file, is_dir]):
            messagebox.showwarning('警告', '禁止文件和文件夹混放!请重新拖拽')
            return

        if all([is_dir, len(new_files) != 1]):
            messagebox.showwarning('警告', '当前版本仅支持拖拽单个文件夹处理!')
            return

        msg = '\n'.join(new_files)
        new_files_msg = ','.join(new_files)
        messagebox.showinfo('您拖放的文件', msg)
        if is_dir:
            self.is_dir = True
        else:
            self.is_file = True

        self.file_paths = new_files
        self.new_files.set(new_files_msg)
        self.root_path.set('')
        self.open_btn['state'] = DISABLED
        self.enter_btn['state'] = NORMAL


if __name__ == '__main__':
    root = Tk()
    root.title('批量修复文件原始格式!')
    width, height, float_x, float_y = count_w_h_x_y(root)
    root.geometry(f'{width}x{height}+{float_x}+{float_y}')  # 设置窗口大小 左上角X,Y坐标
    app = TkApplication(master=root)

    root.mainloop()


新版本的下载链接:
链接:https://pan.baidu.com/s/12YVilZLB6WO58J_R7PYhig?pwd=52pj
提取码:52pj
--来自百度网盘超级会员V8的分享

免费评分

参与人数 1吾爱币 +1 热心值 +1 收起 理由
wdlla2 + 1 + 1  

查看全部评分

wkjxs2015 发表于 2023-8-24 10:17
拿几何画板课件试了一下,没用,改不过来。
少马石 发表于 2023-8-24 10:17
这个怎么识别文件原有的格式?
henancappucc 发表于 2023-8-24 10:18
下来试试看
 楼主| 141442478 发表于 2023-8-24 10:30
wkjxs2015 发表于 2023-8-24 10:17
拿几何画板课件试了一下,没用,改不过来。

        image:jpg,png,gif,web,cr2,tif,bmp,jxr,psd,ico
        video:mp4,m4v,mkv,web,mov,avi,wmv,mpg,flv
        audio:mid,mp3,m4a,ogg,flac,wav,amr
        application: epub,zip,tar,rar,gz,bz2,7z,xz,pdf,exe,swf,rtf,eot,ps,sqlite,nes,crx,cab,deb,ar,Z,lz
        font: woff,woff2,ttf,otf
        目前源文件的格式支持以上类型的!
awxzw 发表于 2023-8-24 10:37
支持下楼主!
阿里巴巴董事长 发表于 2023-8-24 18:04
支持                                            .
wdlla2 发表于 2023-8-24 19:51
本帖最后由 wdlla2 于 2023-8-25 13:10 编辑

建议增加拖放操作。比如拖到界面,或者,不用打开软件,直接拖到图标上就自动处理了
jjwldxsk2023 发表于 2023-8-24 20:24
感谢分享
您需要登录后才可以回帖 登录 | 注册[Register]

本版积分规则 提醒:禁止复制他人回复等『恶意灌水』行为,违者重罚!

快速回复 收藏帖子 返回列表 搜索

RSS订阅|小黑屋|处罚记录|联系我们|吾爱破解 - LCG - LSG ( 京ICP备16042023号 | 京公网安备 11010502030087号 )

GMT+8, 2024-5-1 20:36

Powered by Discuz!

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表