Python学习 - 面向对象学习-文件分类小测试

python 复制代码
import os
import shutil
import json

class FileOrganizer:
    def __init__(self, log_file="file_move.log"):
        self.log_file = log_file
        self.ensure_log_file()

    # 检查移动日志
    def ensure_log_file(self):
        """确保日志文件存在,如果不存在则创建一个空的 JSON 数组"""
        if not os.path.exists(self.log_file):
            with open(self.log_file, "w", encoding="utf-8") as f:
                json.dump([], f, ensure_ascii=False, indent=4)
            print(f"已创建日志文件: {self.log_file}")
        else:
            print(f"日志文件已存在: {self.log_file}")

    # 文件分类
    def classify_files(self, folder_path):
        """按扩展名分类文件"""
        if not os.path.exists(folder_path):
            print("指定的文件夹不存在")
            return

        move_log = []

        for file_name in os.listdir(folder_path):
            file_path = os.path.join(folder_path, file_name)

            # 跳过文件夹和日志文件
            if os.path.isdir(file_path) or file_name == os.path.basename(self.log_file):
                continue

            file_ext = os.path.splitext(file_name)[1].lower()

            # 可根据需要添加文件类型
            if file_ext in ['.txt', '.doc', '.docx']:
                sub_folder = 'Text'
            elif file_ext in ['.jpg', '.jpeg', '.png', '.gif', '.bmp']:
                sub_folder = 'Images'
            elif file_ext in ['.mp4', '.avi', '.mkv']:
                sub_folder = 'Videos'
            elif file_ext in ['.mp3', '.wav']:
                sub_folder = 'Audio'
            elif file_ext in ['.rar', '.zip', '.7z']:
                sub_folder = 'Compressed'
            else:
                sub_folder = 'Others'

            target_folder = os.path.join(folder_path, sub_folder)
            os.makedirs(target_folder, exist_ok=True)

            new_path = os.path.join(target_folder, file_name)
            shutil.move(file_path, new_path)

            move_log.append({"old": file_path, "new": new_path})
            print(f"已移动文件: {file_name} -> {sub_folder}")

        self.update_log(move_log)
        print(f"操作完成,日志已更新到 {self.log_file}")

    # 更新移动日志
    def update_log(self, move_log):
        """追加日志记录"""
        with open(self.log_file, "r+", encoding="utf-8") as f:
            existing_log = json.load(f)
            existing_log.extend(move_log)
            f.seek(0)
            json.dump(existing_log, f, ensure_ascii=False, indent=4)

    # 回滚操作
    def rollback(self):
        """根据日志回滚文件"""
        if not os.path.exists(self.log_file):
            print("没有找到日志文件,无法回滚")
            return

        with open(self.log_file, "r", encoding="utf-8") as f:
            move_log = json.load(f)

        for record in move_log:
            old_path = record["old"]
            new_path = record["new"]

            if os.path.exists(new_path):
                os.makedirs(os.path.dirname(old_path), exist_ok=True)
                shutil.move(new_path, old_path)
                print(f"已回滚文件: {os.path.basename(new_path)} -> 原始位置")

        print("回滚完成")

    def run(self):
        """交互模式"""
        print("请选择操作:")
        print("1. 文件分类")
        print("2. 回滚操作")
        choice = input("输入选项 (1 或 2): ").strip()

        if choice == "1":
            folder_path = input("请输入要分类的文件夹路径: ").strip()
            self.classify_files(folder_path)
        elif choice == "2":
            self.rollback()
        else:
            print("无效选项,请重新运行程序。")


def main():
    organizer = FileOrganizer()
    organizer.run()

if __name__ == "__main__":
    main()
  • 运行代码

  • 选择1或2进行下一步操作

-选择目录路径,进行文件整理

相关推荐
光影少年14 小时前
rn如何和原生进行通信,是单线程还是多线程,通信方式都有哪些
前端·react native·react.js·taro
好大哥呀14 小时前
Java Web的学习路径
java·前端·学习
f***147714 小时前
SpringBoot实战:高效实现API限流策略
java·spring boot·后端
on the way 12314 小时前
day06-SpringDI 依赖注入
java·spring
HashTang14 小时前
【AI 编程实战】第 7 篇:登录流程设计 - 多场景、多步骤的优雅实现
前端·uni-app·ai编程
cos15 小时前
Fork 主题如何更新?基于 Ink 构建主题更新 CLI 工具
前端·javascript·git
小满zs15 小时前
Next.js第二十一章(环境变量)
前端·next.js
C***115015 小时前
Spring aop 五种通知类型
java·前端·spring
BD_Marathon15 小时前
SpringBoot——多环境开发配置
java·spring boot·后端