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 分钟前
不改一行官方源码:用一个插件把 DeepSeek Harness 换成「平安one」
前端
涛涛ing19 分钟前
2026年,你选的不再是框架,是渲染模型
前端
知守观20 分钟前
同一个团队两套分包:DDD 四层落地后,domain 层最大的类还是 5885 行
java·后端·领域驱动设计
AiMan24 分钟前
Perplexity还是不可导出左侧所有对话,只能单条内容,方法不对吗
前端
文丑颜不良啊36 分钟前
LeetCode2541~2560题目解析
java·leetcode
AiMan41 分钟前
千问生成的内容能否下载吗?
前端
北城笑笑42 分钟前
Vue 109 ,从零搭建 Vue3 + Electron 工程:生态、安全桥接与打包选型( Vue + Electron )
前端·javascript·vue.js·安全·electron·vue
瑞雪兆丰年兮1 小时前
JavaWeb-day11-SpringBootWeb案例(文件上传)
java·运维·服务器·javaweb·oss
JarvanMo1 小时前
Flutter 3.50 & Dart 3.14发布,一起看看有哪些变化!
前端
莪_幻尘1 小时前
4 个 3D 游戏,总体积 3.82MB:拆解 Claude 的 one-shot 工程链路
前端·ai编程·three.js