PYTHON 实现智能文件管理系统

Python远程文件管理系统:从协议设计到企业级部署的完整技术实践 在数字化转型加速的今天,企业级文件管理需求呈现爆发式增长。传统FTP协议因安全性不足、扩展性有限等问题逐渐被淘汰,而基于Python构建的现代远程文件管理系统,凭借其灵活的协议设计、跨平台兼容性和强大的扩展能力,正在成为开发者的首选方案。本文将通过一个完整的实战案例,深入解析如何构建支持断点续传、多线程并发、图形化界面的企业级文件管理系统,并分享在金融级安全标准下的部署经验。 阅读详情

功能描述

这个智能文件管理系统提供以下高级功能:

  1. 多平台文件操作抽象层
  2. 智能文件分类与组织
  3. 自动化文件备份与同步
  4. 内容感知搜索
  5. 文件变化监控
  6. 重复文件检测
  7. 自动文件转换
  8. 安全删除与恢复
  9. 文件权限管理
  10. 可视化文件分析

代码实现

import os
import sys
import re
import hashlib
import time
import shutil
import fnmatch
import mimetypes
import datetime
import threading
import queue
import platform
import stat
import zipfile
import tarfile
import json
import csv
import tempfile
from enum import Enum, auto
from typing import (
    Any, Dict, List, Optional, Tuple, Union, 
    Callable, Iterator, Set, NamedTuple, Deque
)
from dataclasses import dataclass, field
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed
import watchdog
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import magic
from PIL import Image, UnidentifiedImageError
import pytesseract
from PyPDF2 import PdfReader
import pandas as pd
import numpy as np
from sklearn.cluster import KMeans
from sklearn.feature_extraction.text import TfidfVectorizer
from cryptography.fernet import Fernet
import requests
from bs4 import BeautifulSoup
import filetype
import exifread
import py7zr
import rarfile
import patoolib

设置日志
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger('SmartFileManager')

class FileCategory(Enum):
    DOCUMENT = auto()
    IMAGE = auto()
    AUDIO = auto()
    VIDEO = auto()
    ARCHIVE = auto()
    CODE = auto()
    DATA = auto()
    EXECUTABLE = auto()
    CONFIG = auto()
    TEMPORARY = auto()
    OTHER = auto()

class FileOperation(Enum):
    COPY = auto()
    MOVE = auto()
    DELETE = auto()
    RENAME = auto()
    COMPRESS = auto()
    EXTRACT = auto()
    CONVERT = auto()
    BACKUP = auto()
    SYNC = auto()

class FileSecurityLevel(Enum):
    PUBLIC = auto()
    INTERNAL = auto()
    CONFIDENTIAL = auto()
    SECRET = auto()

@dataclass
class FileMetadata:
    path: str
    size: int
    created: float
    modified: float
    accessed: float
    category: FileCategory
    mime_type: str
    extension: str
    security_level: FileSecurityLevel = FileSecurityLevel.PUBLIC
    tags: List[str] = field(default_factory=list)
    checksum: Optional[str] = None
    thumbnail: Optional[str] = None
    exif: Optional[Dict[str, Any]] = None
    content_preview: Optional[str] = None

@dataclass
class FileOperationTask:
    operation_id: str
    operation_type: FileOperation
    source: Union[str, List[str]]
    destination: Optional[str] = None
    parameters: Dict[str, Any] = field(default_factory=dict)
    status: str = "pending"
    progress: float = 0.0
    created_at: float = field(default_factory=time.time)
    completed_at: Optional[float] = None
    error: Optional[str] = None

class FileChangeEvent(NamedTuple):
    event_type: str
    src_path: str
    dest_path: Optional[str] = None
    timestamp: float = field(default_factory=time.time)

class SmartFileManager:
    """智能文件管理系统"""
    
    def __init__(self, 
                 root_dir: Optional[str] = None,
                 max_workers: int = 10,
                 enable_monitoring: bool = True,
                 enable_indexing: bool = True,
                 encryption_key: Optional[str] = None):
        
        # 初始化基本属性
        self.root_dir = root_dir or os.getcwd()
        self.max_workers = max_workers
        self.enable_monitoring = enable_monitoring
        self.enable_indexing = enable_indexing
        self.encryption_key = encryption_key or Fernet.generate_key().decode()
        self.fernet = Fernet(self.encryption_key.encode())
        
        # 初始化组件
        self.file_index: Dict[str, FileMetadata] = {}
        self.operation_queue: queue.Queue = queue.Queue()
        self.completed_operations: Dict[str, FileOperationTask] = {}
        self.change_events: Deque[FileChangeEvent] = deque(maxlen=1000)
        self.duplicate_files: Dict[str, List[str]] = {}
        self.file_categories: Dict[FileCategory, List[str]] = {cat: [] for cat in FileCategory}
        
        # 初始化执行器
        self.executor = ThreadPoolExecutor(max_workers=max_workers)
        
        # 初始化文件监控
        if enable_monitoring:
            self.observer = Observer()
            self.event_handler = FileChangeHandler(self)
            self.observer.schedule(self.event_handler, self.root_dir, recursive=True)
            self.observer.start()
        
        # 初始化文件索引
        if enable_indexing:
            self._build_initial_index()
        
        # 启动后台任务
        self._running = True
        self.operation_thread = threading.Thread(target=self._process_operations, daemon=True)
        self.operation_thread.start()
        
        logger.info(f"Initialized Smart File Manager at {self.root_dir}")
    
    def _build_initial_index(self):
        """构建初始文件索引"""
        logger.info("Building initial file index...")
        
        def index_file(file_path: str):
            try:
                metadata = self._get_file_metadata(file_path)
                self.file_index[file_path] = metadata
                self.file_categories[metadata.category].append(file_path)
                
                # 计算文件校验和
                self._calculate_checksum(file_path)
                
            except Exception as e:
                logger.error(f"Failed to index file {file_path}: {str(e)}")
        
        # 使用线程池并行索引文件
        with ThreadPoolExecutor(max_workers=self.max_workers) as executor:
            futures = []
            
            for root, dirs, files in os.walk(self.root_dir):
                for file in files:
                    file_path = os.path.join(root, file)
                    futures.append(executor.submit(index_file, file_path))
            
            for future in as_completed(futures):
                try:
                    future.result()
                except Exception as e:
                    logger.error(f"File indexing error: {str(e)}")
        
        # 识别重复文件
        self._find_duplicate_files()
        
        logger.info(f"Initial file index completed. Total files: {len(self.file_index)}")
    
    def _get_file_metadata(self, file_path: str) -> FileMetadata:
        """获取文件元数据"""
        try:
            stat_info = os.stat(file_path)
            
            # 确定文件类型和类别
            mime_type = magic.from_file(file_path, mime=True)
            extension = os.path.splitext(file_path)[1].lower()
            category = self._determine_file_category(file_path, mime_type, extension)
            
            # 获取EXIF数据(如果是图片)
            exif_data = None
            if category == FileCategory.IMAGE:
                exif_data = self._get_exif_data(file_path)
            
            # 获取内容预览
            content_preview = self._get_content_preview(file_path, category)
            
            return FileMetadata(
                path=file_path,
                size=stat_info.st_size,
                created=stat_info.st_ctime,
                modified=stat_info.st_mtime,
                accessed=stat_info.st_atime,
                category=category,
                mime_type=mime_type,
                extension=extension,
                exif=exif_data,
                content_preview=content_preview
            )
        
        except Exception as e:
            logger.error(f"Failed to get metadata for {file_path}: {str(e)}")
            raise
    
    def _determine_file_category(self, file_path: str, mime_type: str, extension: str) -> FileCategory:
        """确定文件类别"""
        # 文档类型
        document_exts = {'.pdf', '.doc', '.docx', '.ppt', '.pptx', '.xls', '.xlsx', '.txt', '.rtf', '.odt'}
        # 图片类型
        image_exts = {'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.tiff', '.webp', '.svg'}
        # 音频类型
        audio_exts = {'.mp3', '.wav', '.ogg', '.flac', '.aac', '.wma'}
        # 视频类型
        video_exts = {'.mp4', '.avi', '.mkv', '.mov', '.wmv', '.flv', '.webm'}
        # 压缩包类型
        archive_exts = {'.zip', '.rar', '.7z', '.tar', '.gz', '.bz2'}
        # 代码类型
        code_exts = {'.py', '.js', '.java', '.c', '.cpp', '.h', '.html', '.css', '.php', '.sh', '.go', '.rs'}
        # 数据文件
        data_exts = {'.csv', '.json', '.xml', '.yaml', '.yml', '.sql', '.db', '.sqlite'}
        # 可执行文件
        executable_exts = {'.exe', '.dll', '.so', '.dylib', '.bin', '.app', '.msi'}
        # 配置文件
        config_exts = {'.conf', '.config', '.ini', '.cfg', '.env'}
        # 临时文件
        temp_exts = {'.tmp', '.temp', '.swp', '.bak', '~'}
        
        if extension in document_exts or 'document' in mime_type or 'text/' in mime_type:
            return FileCategory.DOCUMENT
        elif extension in image_exts or 'image/' in mime_type:
            return FileCategory.IMAGE
        elif extension in audio_exts or 'audio/' in mime_type:
            return FileCategory.AUDIO
        elif extension in video_exts or 'video/' in mime_type:
            return FileCategory.VIDEO
        elif extension in archive_exts or 'archive' in mime_type or 'compressed' in mime_type:
            return FileCategory.ARCHIVE
        elif extension in code_exts or 'text/x-' in mime_type or 'application/x-' in mime_type:
            return FileCategory.CODE
        elif extension in data_exts or 'data' in mime_type:
            return FileCategory.DATA
        elif extension in executable_exts or 'application/' in mime_type:
            return FileCategory.EXECUTABLE
        elif extension in config_exts:
            return FileCategory.CONFIG
        elif extension in temp_exts:
            return FileCategory.TEMPORARY
        else:
            return FileCategory.OTHER
    
    def _get_exif_data(self, file_path: str) -> Optional[Dict[str, Any]]:
        """获取图片的EXIF数据"""
        try:
            with open(file_path, 'rb') as f:
                tags = exifread.process_file(f)
                if tags:
                    return {str(k): str(v) for k, v in tags.items()}
        except Exception:
            return None
    
    def _get_content_preview(self, file_path: str, category: FileCategory) -> Optional[str]:
        """获取文件内容预览"""
        try:
            if category == FileCategory.DOCUMENT:
                if file_path.lower().endswith('.pdf'):
                    with open(file_path, 'rb') as f:
                        reader = PdfReader(f)
                        text = '\n'.join([page.extract_text() for page in reader.pages[:2]])
                        return text[:500] if text else None
                elif file_path.lower().endswith(('.txt', '.csv', '.json', '.xml')):
                    with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                        return f.read(500)
            
            elif category == FileCategory.IMAGE:
                try:
                    img = Image.open(file_path)
                    img.thumbnail((100, 100))
                    thumb_path = os.path.join(tempfile.gettempdir(), f"thumb_{os.path.basename(file_path)}.jpg")
                    img.save(thumb_path, 'JPEG')
                    return thumb_path
                except UnidentifiedImageError:
                    return None
            
            elif category == FileCategory.CODE:
                with open(file_path, 'r', encoding='utf-8', errors='ignore') as f:
                    return f.read(500)
            
            return None
        except Exception:
            return None
    
    def _calculate_checksum(self, file_path: str, force: bool = False) -> Optional[str]:
        """计算文件校验和"""
        if file_path in self.file_index and self.file_index[file_path].checksum and not force:
            return self.file_index[file_path].checksum
        
        try:
            hash_md5 = hashlib.md5()
            with open(file_path, "rb") as f:
                for chunk in iter(lambda: f.read(4096), b""):
                    hash_md5.update(chunk)
            
            checksum = hash_md5.hexdigest()
            
            if file_path in self.file_index:
                self.file_index[file_path].checksum = checksum
            
            return checksum
        except Exception as e:
            logger.error(f"Failed to calculate checksum for {file_path}: {str(e)}")
            return None
    
    def _find_duplicate_files(self):
        """查找重复文件"""
        checksum_map: Dict[str, List[str]] = {}
        
        for file_path, metadata in self.file_index.items():
            if metadata.checksum:
                if metadata.checksum not in checksum_map:
                    checksum_map[metadata.checksum] = []
                checksum_map[metadata.checksum].append(file_path)
        
        self.duplicate_files = {
            checksum: paths for checksum, paths in checksum_map.items() 
            if len(paths) > 1
        }
        
        logger.info(f"Found {len(self.duplicate_files)} sets of duplicate files")
    
    def _process_operations(self):
        """处理文件操作队列"""
        while self._running:
            try:
                task = self.operation_queue.get(timeout=1)
                if task is None:
                    continue
                
                logger.info(f"Processing operation {task.operation_id}: {task.operation_type.name}")
                
                try:
                    task.status = "processing"
                    
                    if task.operation_type == FileOperation.COPY:
                        self._copy_file(task)
                    elif task.operation_type == FileOperation.MOVE:
                        self._move_file(task)
                    elif task.operation_type == FileOperation.DELETE:
                        self._delete_file(task)
                    elif task.operation_type == FileOperation.RENAME:
                        self._rename_file(task)
                    elif task.operation_type == FileOperation.COMPRESS:
                        self._compress_files(task)
                    elif task.operation_type == FileOperation.EXTRACT:
                        self._extract_archive(task)
                    elif task.operation_type == FileOperation.CONVERT:
                        self._convert_file(task)
                    elif task.operation_type == FileOperation.BACKUP:
                        self._backup_files(task)
                    elif task.operation_type == FileOperation.SYNC:
                        self._sync_files(task)
                    
                    task.status = "completed"
                    task.completed_at = time.time()
                    self.completed_operations[task.operation_id] = task
                    
                except Exception as e:
                    task.status = "failed"
                    task.error = str(e)
                    logger.error(f"Operation {task.operation_id} failed: {str(e)}")
                
                self.operation_queue.task_done()
            
            except queue.Empty:
                continue
    
    def _copy_file(self, task: FileOperationTask):
        """复制文件操作"""
        source = task.source
        dest = task.destination
        
        if isinstance(source, list):
            # 批量复制
            for src in source:
                dest_path = os.path.join(dest, os.path.basename(src))
                self._perform_copy(src, dest_path, task)
        else:
            # 单个文件复制
            if os.path.isdir(source):
                # 复制整个目录
                shutil.copytree(source, dest)
                task.progress = 100.0
            else:
                # 复制单个文件
                self._perform_copy(source, dest, task)
    
    def _perform_copy(self, src: str, dest: str, task: FileOperationTask):
        """执行实际的文件复制"""
        try:
            # 确保目标目录存在
            os.makedirs(os.path.dirname(dest), exist_ok=True)
            
            # 使用shutil.copy2保留元数据
            shutil.copy2(src, dest)
            
            # 更新文件索引
            if self.enable_indexing:
                metadata = self._get_file_metadata(dest)
                self.file_index[dest] = metadata
                self.file_categories[metadata.category].append(dest)
            
            task.progress = 100.0
        except Exception as e:
            raise RuntimeError(f"Failed to copy {src} to {dest}: {str(e)}")
    
    def _move_file(self, task: FileOperationTask):
        """移动文件操作"""
        source = task.source
        dest = task.destination
        
        if isinstance(source, list):
            # 批量移动
            for src in source:
                dest_path = os.path.join(dest, os.path.basename(src))
                self._perform_move(src, dest_path, task)
        else:
            # 单个文件移动
            self._perform_move(source, dest, task)
    
    def _perform_move(self, src: str, dest: str, task: FileOperationTask):
        """执行实际的文件移动"""
        try:
            # 确保目标目录存在
            os.makedirs(os.path.dirname(dest), exist_ok=True)
            
            # 使用shutil.move移动文件
            shutil.move(src, dest)
            
            # 更新文件索引
            if self.enable_indexing:
                if src in self.file_index:
                    metadata = self.file_index.pop(src)
                    metadata.path = dest
                    self.file_index[dest] = metadata
                    
                    # 更新类别列表
                    if src in self.file_categories[metadata.category]:
                        self.file_categories[metadata.category].remove(src)
                        self.file_categories[metadata.category].append(dest)
            
            task.progress = 100.0
        except Exception as e:
            raise RuntimeError(f"Failed to move {src} to {dest}: {str(e)}")
    
    def _delete_file(self, task: FileOperationTask):
        """删除文件操作"""
        source = task.source
        
        if isinstance(source, list):
            # 批量删除
            for src in source:
                self._perform_delete(src, task)
        else:
            # 单个文件删除
            self._perform_delete(source, task)
    
    def _perform_delete(self, path: str, task: FileOperationTask):
        """执行实际的文件删除"""
        try:
            if os.path.isdir(path):
                # 删除目录
                shutil.rmtree(path)
            else:
                # 删除文件
                os.remove(path)
            
            # 更新文件索引
            if self.enable_indexing and path in self.file_index:
                metadata = self.file_index.pop(path)
                
                # 更新类别列表
                if path in self.file_categories[metadata.category]:
                    self.file_categories[metadata.category].remove(path)
            
            task.progress = 100.0
        except Exception as e:
            raise RuntimeError(f"Failed to delete {path}: {str(e)}")
    
    def _rename_file(self, task: FileOperationTask):
        """重命名文件操作"""
        source = task.source
        dest = task.destination
        
        if isinstance(source, list):
            raise ValueError("Rename operation only supports single file")
        
        try:
            # 执行重命名
            os.rename(source, dest)
            
            # 更新文件索引
            if self.enable_indexing and source in self.file_index:
                metadata = self.file_index.pop(source)
                metadata.path = dest
                self.file_index[dest] = metadata
                
                # 更新类别列表
                if source in self.file_categories[metadata.category]:
                    self.file_categories[metadata.category].remove(source)
                    self.file_categories[metadata.category].append(dest)
            
            task.progress = 100.0
        except Exception as e:
            raise RuntimeError(f"Failed to rename {source} to {dest}: {str(e)}")
    
    def _compress_files(self, task: FileOperationTask):
        """压缩文件操作"""
        sources = task.source if isinstance(task.source, list) else [task.source]
        dest = task.destination
        compression = task.parameters.get('compression', 'zip')
        
        try:
            if compression == 'zip':
                with zipfile.ZipFile(dest, 'w', zipfile.ZIP_DEFLATED) as zipf:
                    for src in sources:
                        if os.path.isdir(src):
                            for root, dirs, files in os.walk(src):
                                for file in files:
                                    file_path = os.path.join(root, file)
                                    arcname = os.path.relpath(file_path, os.path.dirname(src))
                                    zipf.write(file_path, arcname)
                                    task.progress += 100.0 / len(sources) / len(files)
                        else:
                            zipf.write(src, os.path.basename(src))
                            task.progress += 100.0 / len(sources)
            
            elif compression == 'tar':
                mode = 'w:' + task.parameters.get('tar_compression', '')
                with tarfile.open(dest, mode) as tar:
                    for src in sources:
                        tar.add(src, arcname=os.path.basename(src))
                        task.progress += 100.0 / len(sources)
            
            elif compression == '7z':
                with py7zr.SevenZipFile(dest, 'w') as archive:
                    for src in sources:
                        archive.write(src, os.path.basename(src))
                        task.progress += 100.0 / len(sources)
            
            # 更新文件索引
            if self.enable_indexing:
                metadata = self._get_file_metadata(dest)
                self.file_index[dest] = metadata
                self.file_categories[metadata.category].append(dest)
            
            task.progress = 100.0
        except Exception as e:
            raise RuntimeError(f"Failed to compress files to {dest}: {str(e)}")
    
    def _extract_archive(self, task: FileOperationTask):
        """解压文件操作"""
        source = task.source
        dest = task.destination
        
        try:
            if source.endswith('.zip'):
                with zipfile.ZipFile(source, 'r') as zip_ref:
                    zip_ref.extractall(dest)
                    task.progress = 100.0
            
            elif source.endswith('.tar.gz') or source.endswith('.tgz'):
                with tarfile.open(source, 'r:gz') as tar:
                    tar.extractall(dest)
                    task.progress = 100.0
            
            elif source.endswith('.tar.bz2'):
                with tarfile.open(source, 'r:bz2') as tar:
                    tar.extractall(dest)
                    task.progress = 100.0
            
            elif source.endswith('.7z'):
                with py7zr.SevenZipFile(source, 'r') as archive:
                    archive.extractall(dest)
                    task.progress = 100.0
            
            elif source.endswith('.rar'):
                patoolib.extract_archive(source, outdir=dest)
                task.progress = 100.0
            
            # 更新文件索引
            if self.enable_indexing:
                for root, dirs, files in os.walk(dest):
                    for file in files:
                        file_path = os.path.join(root, file)
                        metadata = self._get_file_metadata(file_path)
                        self.file_index[file_path] = metadata
                        self.file_categories[metadata.category].append(file_path)
            
        except Exception as e:
            raise RuntimeError(f"Failed to extract {source} to {dest}: {str(e)}")
    
    def _convert_file(self, task: FileOperationTask):
        """文件转换操作"""
        source = task.source
        dest = task.destination
        convert_type = task.parameters.get('type')
        
        try:
            if convert_type == 'image':
                # 图片格式转换
                with Image.open(source) as img:
                    img.save(dest)
                    task.progress = 100.0
            
            elif convert_type == 'pdf_to_text':
                # PDF转文本
                with open(source, 'rb') as f:
                    reader = PdfReader(f)
                    text = '\n'.join([page.extract_text() for page in reader.pages])
                
                with open(dest, 'w', encoding='utf-8') as f:
                    f.write(text)
                    task.progress = 100.0
            
            elif convert_type == 'image_to_text':
                # 图片转文本 (OCR)
                text = pytesseract.image_to_string(Image.open(source))
                with open(dest, 'w', encoding='utf-8') as f:
                    f.write(text)
                    task.progress = 100.0
            
            # 更新文件索引
            if self.enable_indexing:
                metadata = self._get_file_metadata(dest)
                self.file_index[dest] = metadata
                self.file_categories[metadata.category].append(dest)
            
        except Exception as e:
            raise RuntimeError(f"Failed to convert {source} to {dest}: {str(e)}")
    
    def _backup_files(self, task: FileOperationTask):
        """备份文件操作"""
        sources = task.source if isinstance(task.source, list) else [task.source]
        dest = task.destination
        backup_type = task.parameters.get('type', 'full')
        
        try:
            timestamp = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
            backup_name = f"backup_{timestamp}"
            
            if backup_type == 'full':
                # 完整备份
                backup_path = os.path.join(dest, f"{backup_name}.zip")
                self._compress_files(FileOperationTask(
                    operation_id=task.operation_id,
                    operation_type=FileOperation.COMPRESS,
                    source=sources,
                    destination=backup_path,
                    parameters={'compression': 'zip'}
                ))
            
            elif backup_type == 'incremental':
                # 增量备份
                pass
            
            task.progress = 100.0
        except Exception as e:
            raise RuntimeError(f"Failed to create backup: {str(e)}")
    
    def _sync_files(self, task: FileOperationTask):
        """同步文件操作"""
        source = task.source
        dest = task.destination
        sync_type = task.parameters.get('type', 'mirror')
        
        try:
            if sync_type == 'mirror':
                # 镜像同步
                pass
            
            elif sync_type == 'two_way':
                # 双向同步
                pass
            
            task.progress = 100.0
        except Exception as e:
            raise RuntimeError(f"Failed to sync files: {str(e)}")
    
    def queue_operation(self, 
                       operation_type: FileOperation,
                       source: Union[str, List[str]],
                       destination: Optional[str] = None,
                       parameters: Optional[Dict[str, Any]] = None) -> str:
        """将文件操作加入队列"""
        operation_id = f"op_{uuid.uuid4().hex[:8]}"
        
        task = FileOperationTask(
            operation_id=operation_id,
            operation_type=operation_type,
            source=source,
            destination=destination,
            parameters=parameters or {}
        )
        
        self.operation_queue.put(task)
        return operation_id
    
    def get_operation_status(self, operation_id: str) -> Optional[Dict[str, Any]]:
        """获取操作状态"""
        if operation_id in self.completed_operations:
            task = self.completed_operations[operation_id]
            return {
                'status': task.status,
                'progress': task.progress,
                'error': task.error,
                'created_at': task.created_at,
                'completed_at': task.completed_at
            }
        
        # 检查是否仍在队列中
        for task in list(self.operation_queue.queue):
            if task.operation_id == operation_id:
                return {
                    'status': task.status,
                    'progress': task.progress,
                    'created_at': task.created_at
                }
        
        return None
    
    def search_files(self,
                   query: str,
                   category: Optional[FileCategory] = None,
                   min_size: Optional[int] = None,
                   max_size: Optional[int] = None,
                   modified_after: Optional[datetime.datetime] = None,
                   modified_before: Optional[datetime.datetime] = None) -> List[Dict[str, Any]]:
        """搜索文件"""
        results = []
        
        for file_path, metadata in self.file_index.items():
            # 应用过滤器
            if category and metadata.category != category:
                continue
            
            if min_size and metadata.size < min_size:
                continue
            
            if max_size and metadata.size > max_size:
                continue
            
            if modified_after and datetime.datetime.fromtimestamp(metadata.modified) < modified_after:
                continue
            
            if modified_before and datetime.datetime.fromtimestamp(metadata.modified) > modified_before:
                continue
            
            # 检查查询匹配
            match = False
            
            # 检查文件名
            if query.lower() in os.path.basename(file_path).lower():
                match = True
            
            # 检查内容预览
            elif metadata.content_preview and query.lower() in metadata.content_preview.lower():
                match = True
            
            # 检查标签
            elif any(query.lower() in tag.lower() for tag in metadata.tags):
                match = True
            
            if match:
                results.append({
                    'path': file_path,
                    'name': os.path.basename(file_path),
                    'size': metadata.size,
                    'modified': datetime.datetime.fromtimestamp(metadata.modified),
                    'category': metadata.category.name,
                    'mime_type': metadata.mime_type,
                    'preview': metadata.content_preview
                })
        
        return results
    
    def analyze_storage(self) -> Dict[str, Any]:
        """分析存储使用情况"""
        analysis = {
            'total_files': len(self.file_index),
            'total_size': sum(meta.size for meta in self.file_index.values()),
            'by_category': {},
            'by_extension': {},
            'largest_files': [],
            'oldest_files': [],
            'duplicate_files': len(self.duplicate_files)
        }
        
        # 按类别分析
        for category, files in self.file_categories.items():
            if files:
                analysis['by_category'][category.name] = {
                    'count': len(files),
                    'size': sum(self.file_index[f].size for f in files)
                }
        
        # 按扩展名分析
        ext_map = {}
        for meta in self.file_index.values():
            if meta.extension not in ext_map:
                ext_map[meta.extension] = {'count': 0, 'size': 0}
            ext_map[meta.extension]['count'] += 1
            ext_map[meta.extension]['size'] += meta.size
        
        analysis['by_extension'] = ext_map
        
        # 最大的文件
        largest = sorted(
            self.file_index.values(),
            key=lambda x: x.size,
            reverse=True
        )[:10]
        
        analysis['largest_files'] = [
            {'path': meta.path, 'size': meta.size}
            for meta in largest
        ]
        
        # 最旧的文件
        oldest = sorted(
            self.file_index.values(),
            key=lambda x: x.modified
        )[:10]
        
        analysis['oldest_files'] = [
            {
                'path': meta.path,
                'modified': datetime.datetime.fromtimestamp(meta.modified),
                'size': meta.size
            }
            for meta in oldest
        ]
        
        return analysis
    
    def cleanup_files(self,
                     categories: Optional[List[FileCategory]] = None,
                     extensions: Optional[List[str]] = None,
                     older_than: Optional[datetime.timedelta] = None,
                     dry_run: bool = True) -> Dict[str, Any]:
        """清理文件"""
        report = {
            'total_freed': 0,
            'files_removed': 0,
            'files_skipped': 0,
            'details': []
        }
        
        now = time.time()
        threshold = now - older_than.total_seconds() if older_than else 0
        
        for file_path, metadata in self.file_index.items():
            # 检查是否匹配清理条件
            match = False
            
            if categories and metadata.category in categories:
                match = True
            
            if extensions and metadata.extension in extensions:
                match = True
            
            if older_than and metadata.modified < threshold:
                match = True
            
            if match:
                try:
                    if not dry_run:
                        os.remove(file_path)
                        report['total_freed'] += metadata.size
                        report['files_removed'] += 1
                        
                        # 更新索引
                        if file_path in self.file_index:
                            self.file_index.pop(file_path)
                        
                        if file_path in self.file_categories[metadata.category]:
                            self.file_categories[metadata.category].remove(file_path)
                    
                    report['details'].append({
                        'path': file_path,
                        'size': metadata.size,
                        'modified': datetime.datetime.fromtimestamp(metadata.modified),
                        'category': metadata.category.name,
                        'action': 'removed' if not dry_run else 'would_remove'
                    })
                
                except Exception as e:
                    report['files_skipped'] += 1
                    report['details'].append({
                        'path': file_path,
                        'error': str(e),
                        'action': 'skipped'
                    })
        
        return report
    
    def close(self):
        """关闭文件管理器"""
        self._running = False
        self.observer.stop()
        self.observer.join()
        self.executor.shutdown(wait=True)
        
        logger.info("Smart File Manager closed")

class FileChangeHandler(FileSystemEventHandler):
    """文件系统事件处理器"""
    
    def __init__(self, file_manager: SmartFileManager):
        self.file_manager = file_manager
    
    def on_created(self, event):
        """文件创建事件"""
        if not event.is_directory:
            change_event = FileChangeEvent(
                event_type='created',
                src_path=event.src_path
            )
            self.file_manager.change_events.append(change_event)
            
            # 更新文件索引
            if self.file_manager.enable_indexing:
                try:
                    metadata = self.file_manager._get_file_metadata(event.src_path)
                    self.file_manager.file_index[event.src_path] = metadata
                    self.file_manager.file_categories[metadata.category].append(event.src_path)
                except Exception as e:
                    logger.error(f"Failed to index new file {event.src_path}: {str(e)}")
    
    def on_deleted(self, event):
        """文件删除事件"""
        if not event.is_directory:
            change_event = FileChangeEvent(
                event_type='deleted',
                src_path=event.src_path
            )
            self.file_manager.change_events.append(change_event)
            
            # 更新文件索引
            if self.file_manager.enable_indexing and event.src_path in self.file_manager.file_index:
                metadata = self.file_manager.file_index.pop(event.src_path)
                
                # 更新类别列表
                if event.src_path in self.file_manager.file_categories[metadata.category]:
                    self.file_manager.file_categories[metadata.category].remove(event.src_path)
    
    def on_modified(self, event):
        """文件修改事件"""
        if not event.is_directory:
            change_event = FileChangeEvent(
                event_type='modified',
                src_path=event.src_path
            )
            self.file_manager.change_events.append(change_event)
            
            # 更新文件索引
            if self.file_manager.enable_indexing and event.src_path in self.file_manager.file_index:
                try:
                    metadata = self.file_manager._get_file_metadata(event.src_path)
                    self.file_manager.file_index[event.src_path] = metadata
                    
                    # 更新类别列表
                    old_category = None
                    for cat, files in self.file_manager.file_categories.items():
                        if event.src_path in files:
                            old_category = cat
                            break
                    
                    if old_category and old_category != metadata.category:
                        self.file_manager.file_categories[old_category].remove(event.src_path)
                        self.file_manager.file_categories[metadata.category].append(event.src_path)
                except Exception as e:
                    logger.error(f"Failed to update index for modified file {event.src_path}: {str(e)}")
    
    def on_moved(self, event):
        """文件移动/重命名事件"""
Python实现文件管理 在Python语言中,我们也可以通过使用内置模块和第三方库对文件进行创建、读取、写入和删除等操作,实现文件管理的功能。上述代码将打开名为test.txt的文件,并读取其中的内容。需要注意的是,读取完文件后,需要使用close方法关闭文件。需要注意的是,写入数据完成后,需要使用close方法关闭文件。综上所述,我们可以通过使用Python中的内置模块和第三方库来实现文件管理的功能,包括文件的创建、读取、写入和删除等操作。在Python中,使用read函数可以读取文件中的内容。Python实现文件管理。 阅读详情

相关推荐

python之文件操作实现学生管理系统

  Python 是一门易于学习、功能强大的编程语言。它提供了高效的高级数据结构,还能简单有效地面向对象编程。Python 优雅的语法和动态类型以及解释型语言的本质,使它成为多数平台上写脚本和快速开发应用的理想语言。下面我们来介绍一下python的文件操作实现学生管理系统相关知识。  增加保存学生信息到文件的功能和从文件中读取学生信息到程序的功能。 (1)在显示菜单列表的函数中,增加“保存数据”和“恢复数据”选项。 (2)增加函数,用于将学生数据保存到文件中,write()方法的参数必须是字符串类型,因此,

jiankang66的博客 2419

python--文件管理系统

采用PyQt5进行图形化开发,并应用,增加较多图标,较为美观提供了菜单栏工具和右键选择菜单两种操作方式。

实力派,无需多言! 2040

python文件管理系统各种版本

python文件管理系统的各种版本 包含:初级版、函数版、文件版

Python实现文件管理系统

文章目录第一题:![在这里插入代码片](https://img-blog.csdnimg.cn/740485106ca64e30a037b9f4f6e5ebec.png)第二题:使用面向对象实现一个栈 第一题: ` import pickle from re import T import os import hashlib import datetime from secrets import choice import sys import hashutil as hashutil from os im

qq_50589028的博客 5490

Zephyr、FreeRTOS 和 RT-Thread

你是…更适合用嵌入式新手,刚接触 RTOSFreeRTOS(入门简单)IoT 项目开发,需要 BLE/WiFi/MQTTZephyr(协议全)想快速构建可部署的产品Zephyr(模块统一)只做单个任务或简单状态机控制FreeRTOS(轻量)做平台化、持续集成、自动测试Zephyr(CI 支持强)

is0815的博客 2269

双通道中频信号数字下变频及相位差估计(FPGA)

双通道中频信号数字下变频及相位差估计实验 一、上框图(通俗易懂) 二、实验要求 1、 用点频信号模拟中频信号:中频信号由DDS1和DDS2产生。具体产生方法见第2点。 2、 DDS1和 DDS2:调用IPcore里的数字信号处理中的NCO模块,工作时钟为100MHz,数据率即为100MHz,DDS1和DDS2的频率为:(学号后三位+500)Khz+f0(可设为20MHz);输出为16位;DDS1...

qq_39809425的博客 6955

基于Python的文件管理系统的设计与实现

Java简介Java是一种面向对象的静态式编程语言。Java编程语言具有多线程和对象定向的特点。其特点是根据方案的属性将方案分为几个不同的模块,这些模块是封闭的和多样化的,在申请过程中具有很强的独立性。Java语言在计算机软件开发过程中的运用可以达到交互操作的目的,通过各种形式的交换,可以有效地处理所需的数据,从而确保计算机软件开发的可控性和可见性。开发java语言时,保留了网络接口,Java保留的缺省网络接口可以与web应用程序编程所依赖的类别库相匹配。

weixin_63982010的博客 816

128x64 OLED屏的救星:手把手教你用纯C实现轻量级多级菜单

本文针对资源受限的单片机开发场景,提供了一套用纯C语言实现128x64 OLED屏轻量级多级菜单的完整方案。该方案摒弃了传统的树形指针结构,创新性地采用哈希表进行菜单项管理,核心代码不足200行,内存占用极低,逻辑清晰且易于维护。文章详细阐述了架构设计、实战演练及性能优化技巧,是STM32、ESP8266等小内存MCU项目的理想选择。

table的专栏 231

小白盘如何用AI技术实现智能文件管理

最近在整理电脑文件时,发现自己的文档、图片、视频全都混在一起,找个文件要花半天时间。经过一番摸索,终于用Python实现了一个叫"小白盘"的工具,今天就来分享下开发过程和经验。我测试时发现,平台提供的预置环境让机器学习项目的搭建变得特别简单,而且可以直接将完成的Web应用一键部署上线,省去了繁琐的服务器配置过程。对于初学者来说,这种集成化的开发体验真的很友好,不用操心环境配置就能专注在核心功能的实现上。希望这个分享能给想做智能工具开发的朋友一些启发,也欢迎大家交流更多AI应用场景的实现思路。

OnyxPanther23的博客 491

Altium Designer实战:手把手教你设计智能车竞赛疯狂电路组赛道(附封装库)

本文详细介绍了使用Altium Designer软件进行智能车竞赛“疯狂电路”组赛道设计的全流程实战指南。从理解比赛规则、搭建设计环境、创建专用元器件封装库,到电路布局、路径规划及设计输出验证,手把手教你高效完成符合计分标准的赛道图纸设计,并附上实用的封装库管理方法。

alice7model的博客 1334

太空安全卫士:基于YOLOv5的空间态势感知系统(实现轨道碰撞预警与太空环境保护)

做完这个项目,你会发现自己完整走过了“数据采集→标注→模型训练→功能集成→界面开发”的毕设全流程,这不仅是技术能力的证明,更是对“技术守护宇宙安全”这一理念的实践。答辩时,你可以重点讲这几点:系统解决了航天监测的哪些痛点、YOLOv5在太空目标检测中的性能优势、系统未来能怎么优化(比如对接航天监测网络、实现实时轨道预测)。未来,这个系统还能往“更智能”的方向发展:比如结合轨道计算预测碰撞风险、开发移动端APP让天文爱好者参与太空垃圾上报、在航天任务中实现全自动避障决策……想象空间很大。

m0_71589036的博客 97

Python+DeepSeek AI打造智能文件管理系统

文件管理是现代办公场景中的常见需求,尤其是面对大量命名混乱的非结构化数据时。通过Python脚本结合DeepSeek AI的多模态能力,可以实现智能化的文件重命名与分类系统。该系统首先利用Watchdog监控文件变动,然后提取文件元数据和内容特征,再通过大模型API生成语义化的命名建议,最后应用规则引擎执行批量操作。这种技术方案不仅解决了传统文件管理工具功能单一的问题,还能适应文档、图片、代码等不同文件类型的处理需求。在实际应用中,该系统显著提升了摄影素材管理、科研文献整理等场景的工作效率,展示了AI技术与

weixin_29800471的博客 88

《ESP32单片机基础入门》第2章:开发环境搭建

【代码】《ESP32单片机基础入门》第2章:开发环境搭建。

2301_79143213的博客 587

探索未来文件管理新纪元:LlamaFS,智能整理您的数字世界

探索未来文件管理新纪元:LlamaFS,智能整理您的数字世界 【免费下载链接】llama-fs A self-organizing file system with llama 3 项目地址: https://gitcode.co...

gitblog_00158的博客 507

安路TangDynasty和FD和JTAG驱动器安装

安路FPGA产品矩阵包含SALPHOENIX高性能、SALEAGLE高性价比和SALELF低功耗三大系列,广泛应用于网络通信、消费电子等领域。配套的TangDynasty(TD)集成开发环境支持标准设计输入,提供完整优化流程与调试工具。简要介绍了TD 6.2.1版本的安装步骤。

wangjie36的博客 1066

Close-By Site Assignment,门店近邻关系在 SAP Retail 物料搜索里的真实价值

SAP零售模块中的"Close-By Site Assignment"功能常被低估,但它在门店现场业务中极为关键。该功能允许预先定义各门店间的近邻关系,当导购或店长查询商品时,系统会自动展示附近门店的库存、价格和促销信息。与单纯的地理距离不同,这种近邻关系可基于调拨频率、业务关联度等业务逻辑定义。维护入口在事务码WSD_CBP中,支持按应用场景(如销售、采购)分别设置不同近邻关系。该功能不同于组织结构,专注于增强搜索体验,特别适合多门店运营场景,能有效提升跨店查询效率。

2007 年 ~ 2025 年,深耕 SAP 技术 18 年 4861

如何将微信机器人收到的图片和文件自动保存到本地?docker-wechatbot-webhook的媒体文件管理指南

你是否在使用微信机器人时遇到过这样的困扰:重要的图片、文件无法自动保存,需要手动下载整理?或者想要搭建一个智能的媒体文件归档系统?docker-wechatbot-webhook为你提供了完整的解决方案。 本文将带你深入探索如何通过配置和扩展,实现微信接收的图片、视频、文件等媒体内容自动保存到指定目录,构建你的个人媒体文件管理系统。 --- ## 📁 为什么需要自动保存媒体文件? 在自动

gitblog_00352的博客 43

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

教育资源数字化获取的技术解决方案:tchMaterial-parser工具深度解析

在教育信息化快速发展的背景下,数字教育资源获取的效率瓶颈日益凸显。国家中小学智慧教育平台作为官方教育资源库,承载着海量电子课本资源,然而其下载流程的技术复杂性成为教育工作者和学生面临的实际挑战。tchMaterial-parser项目针对这一痛点,提供了一套系统化的技术解决方案,通过自动化解析与批量处理机制,优化了教育资源获取的工作流程。 ## 技术架构与实现原理 tchMaterial-pa

gitblog_01110的博客 343

汉书HE8,好用的汇编代码编写工具

汉书HE8,好用的汇编代码编写工具早期编写汇编代码所用功能强大

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

基于Python的作业文件管理系统

摘要:本文设计并实现了一个基于Python语言的作业文件管理系统,采用Django框架和Vue.js技术构建B/S架构。系统针对传统作业管理效率低下等问题,实现了作业发布、提交、批改、成绩管理等全流程数字化。通过MySQL数据库确保数据安全,采用组件化开发提升用户体验。测试表明系统功能完整、性能稳定,为教育信息化提供了高效解决方案。该系统具有技术可行性、经济可行性和操作可行性,对推动教育管理现代化具有重要意义。

2401_86117024的博客 757

LinePhone3.2.7(android端最新版本) sip客户端

SIP客户端For android:LinePhone3.2.7(最新版本),官网地址:http://www.linphone.org/

python+vue基于django/flask的在线文件管理系统java+nodejs-计算机毕业设计

在当今信息时代,随着数字化和网络化的发展,文件管理成为各个领域中不可或缺的一部分。企业、学校、个人等各类组织和用户都需要有效地组织、存储和分享大量的电子文件。传统的文件管理方式已经不能满足快速发展的需求,因此,基于python的在线文件管理系统的开发成为迫切需要的解决方案。

QQ_511008285的博客 1156

如何用VJ-FILTER-BOT打造高效文件管理系统?实用案例分享

VJ-FILTER-BOT是一款功能强大的自动化文件过滤机器人,它能帮助用户轻松构建高效的文件管理系统,实现文件的自动分类、快速检索和智能处理。无论是个人用户还是团队管理者,都能通过这款工具显著提升文件管理效率,减少手动操作带来的繁琐和错误。 ## 为什么选择VJ-FILTER-BOT进行文件管理? 在日常工作和学习中,我们经常会遇到文件杂乱无章、查找困难的问题。VJ-FILTER-BOT作为

gitblog_01040的博客 733
上一篇: PYTHON 实现智能数据管道与实时分析系统
下一篇: PYTHON 实现智能数据清洗与转换框架
安丨
博客等级 码龄4年 3914粉丝 889原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值