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

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

相关推荐
爱吃土豆的马铃薯ㅤㅤㅤㅤㅤㅤㅤㅤㅤ4 分钟前
React 怎么区分导入的是组件还是函数,或者是对象
前端·react.js·前端框架
LYFlied17 分钟前
【每日算法】LeetCode 136. 只出现一次的数字
前端·算法·leetcode·面试·职场和发展
子春一218 分钟前
Flutter 2025 国际化与本地化工程体系:从多语言支持到文化适配,打造真正全球化的应用
前端·flutter
guslegend24 分钟前
Tomact高级使用及原理剖析
java
Code blocks25 分钟前
SpringBoot从0-1集成Minio对象存储
java·spring boot·后端
故渊ZY30 分钟前
MyBatis事务原理与实战指南
java·mybatis
QT 小鲜肉32 分钟前
【Linux命令大全】001.文件管理之file命令(实操篇)
linux·运维·前端·网络·chrome·笔记
HTouying1 小时前
线程池【工具类】
java
深盾科技1 小时前
融合C++与Python:兼顾开发效率与运行性能
java·c++·python
我待_JAVA_如初恋1 小时前
idea创建MavenJavaWeb项目以后,包结构缺java
java·ide·intellij-idea