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进行下一步操作

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

相关推荐
折哥的程序人生 · 物流技术专研8 小时前
第4篇:Lambda 简化策略模式(Java 8+)
java·设计模式·策略模式·函数式编程·lambda·代码简化·扩充系列
researcher-Jiang8 小时前
高性能计算之OpenMP——超算习堂学习1
android·java·学习
随风一样自由9 小时前
【前端独角兽】刚进入前端领域的前端开发用jQuery还是Vue3?
前端·javascript·vue3·jquery
IMPYLH10 小时前
HTML 的 <data> 元素
前端·html
西门吹-禅10 小时前
java springboot N+1问题
java·开发语言·spring boot
YHHLAI10 小时前
[特殊字符] 面试中的 Promise —— 从入门到精通
前端·javascript·面试
DLYSB_10 小时前
生命通道:如何用 HIS 医疗系统直连网络声光终端,打造“零延误”的危急值响应网关?
java·网络·数据库·报警灯
weixin_BYSJ198711 小时前
SpringBoot + MySQL 乒乓球运动员信息管理系统项目实战--附源码04954
java·javascript·spring boot·python·django·flask·php
AI小码11 小时前
LLM 应用的缓存工程:当每次 API 调用都在燃烧成本
java·人工智能·spring·计算机·llm·编程·api
Hui Baby11 小时前
Spring Security
java·后端·spring