HLJ 发布于
2025-09-23 09:02:07
0阅读

python自学教程

查看 Python 版本

python -V
或
python --version

第一个Python程序

test.py 文件代码:

print("Hello, World!")

python 命令执行该脚本文件

python test.py

以上命令输出结果为:

Hello, World!

读取csv文件内容

import csv

with open('output3.csv', mode='r', encoding='utf-8') as file:
    csv_reader = csv.reader(file)
    
    for row in csv_reader:
        print(row)

视频转gif格式动画图片

from moviepy  import VideoFileClip

def video_to_gif(video_path, output_path, start_time=0, end_time=10, fps=10):
    clip = VideoFileClip(video_path).subclipped(start_time, end_time)
    clip.write_gif(output_path, fps=fps)
    print(f'GIF saved to: {output_path}')

video_to_gif('happyfit2.mp4', 'output2.gif', 0, 10)

生成可视化界面代码

import tkinter as tk
 
def say_hello():
    label.config(text="Hello, Tkinter!")
 
app = tk.Tk()
app.title("Hello Tkinter")
 
label = tk.Label(app, text="Press the button")
label.pack(pady=20)
 
button = tk.Button(app, text="Greet", command=say_hello)
button.pack(pady=20)
 
app.mainloop()

将python文件打包成exe可执行文件

安装pyinstaller依赖

pip install pyinstaller

执行知道的py脚本文件

pyinstaller --onefile your_script.py

# 单文件打包
pyinstaller --icon=favicon.ico --onefile test.py

# 单目录打包
pyinstaller --icon=favicon.ico --onedir test.py

# GUI应用(无控制台窗口)
pyinstaller --icon=favicon.ico --windowed --onefile test.py

系统监控工具

import psutil
import time
import matplotlib.pyplot as plt
from datetime import datetime
import json

class SystemMonitor:
    """系统监控工具"""
    
    def __init__(self):
        self.monitoring = False
        self.data = {
            'timestamps': [],
            'cpu_percent': [],
            'memory_percent': [],
            'disk_usage': [],
            'network_sent': [],
            'network_recv': []
        }
    
    def start_monitoring(self, duration=60, interval=1):
        """开始监控系统资源"""
        self.monitoring = True
        start_time = time.time()
        
        print("开始系统监控...")
        print("时间戳 | CPU使用率 | 内存使用率 | 磁盘使用率 | 网络发送 | 网络接收")
        print("-" * 70)
        
        while self.monitoring and (time.time() - start_time) < duration:
            # 获取系统信息
            cpu_percent = psutil.cpu_percent(interval=0.1)
            memory = psutil.virtual_memory()
            disk = psutil.disk_usage('/')
            network = psutil.net_io_counters()
            
            timestamp = datetime.now().strftime("%H:%M:%S")
            
            # 记录数据
            self.data['timestamps'].append(timestamp)
            self.data['cpu_percent'].append(cpu_percent)
            self.data['memory_percent'].append(memory.percent)
            self.data['disk_usage'].append(disk.percent)
            self.data['network_sent'].append(network.bytes_sent)
            self.data['network_recv'].append(network.bytes_recv)
            
            # 打印当前状态
            print(f"{timestamp} | {cpu_percent:>8.1f}% | {memory.percent:>10.1f}% | "
                  f"{disk.percent:>10.1f}% | {network.bytes_sent:>8} | {network.bytes_recv:>8}")
            
            time.sleep(interval)
        
        self.monitoring = False
        print("监控结束")
    
    def stop_monitoring(self):
        """停止监控"""
        self.monitoring = False
    
    def generate_report(self):
        """生成监控报告"""
        if not self.data['timestamps']:
            print("没有监控数据")
            return
        
        report = {
            '监控开始时间': self.data['timestamps'][0],
            '监控结束时间': self.data['timestamps'][-1],
            '数据点数': len(self.data['timestamps']),
            'CPU平均使用率': sum(self.data['cpu_percent']) / len(self.data['cpu_percent']),
            '内存平均使用率': sum(self.data['memory_percent']) / len(self.data['memory_percent']),
            '磁盘平均使用率': sum(self.data['disk_usage']) / len(self.data['disk_usage']),
            '最大CPU使用率': max(self.data['cpu_percent']),
            '最大内存使用率': max(self.data['memory_percent'])
        }
        
        return report
    
    def plot_monitoring_data(self):
        """绘制监控数据图表"""
        if not self.data['timestamps']:
            print("没有数据可绘制")
            return
        
        fig, axes = plt.subplots(2, 2, figsize=(12, 8))
        
        # CPU使用率
        axes[0, 0].plot(self.data['cpu_percent'], 'r-')
        axes[0, 0].set_title('CPU使用率 (%)')
        axes[0, 0].grid(True)
        
        # 内存使用率
        axes[0, 1].plot(self.data['memory_percent'], 'b-')
        axes[0, 1].set_title('内存使用率 (%)')
        axes[0, 1].grid(True)
        
        # 磁盘使用率
        axes[1, 0].plot(self.data['disk_usage'], 'g-')
        axes[1, 0].set_title('磁盘使用率 (%)')
        axes[1, 0].grid(True)
        
        # 网络使用情况
        axes[1, 1].plot(self.data['network_sent'], 'orange', label='发送')
        axes[1, 1].plot(self.data['network_recv'], 'purple', label='接收')
        axes[1, 1].set_title('网络流量')
        axes[1, 1].legend()
        axes[1, 1].grid(True)
        
        plt.tight_layout()
        plt.savefig('system_monitoring.png', dpi=300, bbox_inches='tight')
        plt.show()

# 使用示例
if __name__ == "__main__":
    monitor = SystemMonitor()
    
    # 监控60秒,每秒采集一次数据
    monitor.start_monitoring(duration=60, interval=1)
    
    # 生成报告
    report = monitor.generate_report()
    print(json.dumps(report, indent=2, ensure_ascii=False))
    
    # 绘制图表
    monitor.plot_monitoring_data()

生成二维码

import qrcode

input_URL = "http://www.good1230.com/"

qr = qrcode.QRCode(
    version=1,
    error_correction=qrcode.constants.ERROR_CORRECT_L,
    box_size=15,
    border=4,
)

qr.add_data(input_URL)
qr.make(fit=True)

img = qr.make_image(fill_color="red", back_color="white")
img.save("url_qrcode.png")

print(qr.data_list)

视频转GIF动画

from moviepy.editor import VideoFileClip
import os

def video_to_gif_moviepy(video_path, gif_path, start_time=0, end_time=None, fps=10, resize_ratio=0.5):
    """
    使用moviepy将视频转换为GIF
    
    Args:
        video_path: 视频文件路径
        gif_path: 输出GIF路径
        start_time: 开始时间(秒)
        end_time: 结束时间(秒)
        fps: GIF帧率
        resize_ratio: 缩放比例
    """
    try:
        # 加载视频文件
        video = VideoFileClip(video_path)
        
        # 设置结束时间
        if end_time is None:
            end_time = video.duration
        elif end_time > video.duration:
            end_time = video.duration
        
        # 截取视频片段
        video_clip = video.subclip(start_time, end_time)
        
        # 调整大小(可选)
        if resize_ratio != 1:
            video_clip = video_clip.resize(resize_ratio)
        
        # 转换为GIF
        video_clip.write_gif(
            gif_path,
            fps=fps,
            program='ffmpeg',  # 使用ffmpeg引擎
            verbose=False
        )
        
        # 关闭视频对象
        video.close()
        video_clip.close()
        
        print(f"转换成功!GIF已保存到: {gif_path}")
        print(f"原视频时长: {video.duration:.2f}秒")
        print(f"转换片段: {start_time}-{end_time}秒")
        
        return True
        
    except Exception as e:
        print(f"转换失败: {e}")
        return False

# 使用示例
if __name__ == "__main__":
    video_to_gif_moviepy(
        video_path="happyfit2.mp4",
        gif_path="output.gif",
        start_time=5,      # 从第5秒开始
        end_time=15,       # 到第15秒结束
        fps=8,            # 帧率
        resize_ratio=0.6  # 缩放为原大小的60%
    )

https://www.codewithfaraz.com/article/129/50-python-projects-with-source-code-beginner-to-advanced

Bringing-Old-Photos-Back-to-Life

https://github.com/microsoft/Bringing-Old-Photos-Back-to-Life

步骤 1 [克隆Bringing-Old-Photos-Back-to-Life]

git clone https://github.com/microsoft/Bringing-Old-Photos-Back-to-Life.git

步骤二

步骤三

https://gitcode.com/gh_mirrors/br/Bringing-Old-Photos-Back-to-Life/?utm_source=gitcode_aigc_v1_t1&index=bottom&type=card&&uuid_tt_dd=10_19016671100-1747062536379-196225&isLogin=9&from_id=151938196&from_link=6a57b0871cd622eef031e393912ab1b3

https://blog.csdn.net/gitblog_00598/article/details/151938196

https://blog.51cto.com/zhangxueliang/11709006

https://blog.csdn.net/cdchjn/article/details/128174210

Python3编写的各种大小程序,包含从零学Python系列、12306抢票、省市区地址库以及系列网站爬虫等学习源码

https://github.com/gxcuizy/Python/

图片高清处理python 软件Real-ESRGAN下载地址

https://github.com/xinntao/Real-ESRGAN/releases/tag/v0.2.5.0

桌面文件整理小工具

import os
import shutil
from pathlib import Path
import logging
from datetime import datetime

# 设置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('desktop_organizer.log', encoding='utf-8'),
        logging.StreamHandler()
    ]
)

class DesktopOrganizer:
    def __init__(self, desktop_path=None):
        """初始化桌面整理器"""
        if desktop_path is None:
            # 自动检测桌面路径(支持Windows、macOS、Linux)
            self.desktop_path = self.get_desktop_path()
        else:
            self.desktop_path = Path(desktop_path)
        
        # 文件类型分类
        self.file_categories = {
            'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg', '.webp', '.tiff'],
            'Documents': ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.odt', '.xls', '.xlsx', '.ppt', '.pptx'],
            'Archives': ['.zip', '.rar', '.7z', '.tar', '.gz', '.iso'],
            'Programs': ['.exe', '.msi', '.dmg', '.pkg', '.deb', '.rpm'],
            'Media': ['.mp4', '.avi', '.mkv', '.mov', '.wmv', '.mp3', '.wav', '.flac', '.aac'],
            'Code': ['.py', '.java', '.cpp', '.c', '.html', '.css', '.js', '.json', '.xml', '.sql'],
            'Design': ['.psd', '.ai', '.sketch', '.fig', '.xd'],
            'Data': ['.csv', '.json', '.xml', '.db', '.sqlite']
        }
        
        # 其他文件分类
        self.other_folder = 'Others'
        
        logging.info(f"桌面整理器初始化完成,桌面路径: {self.desktop_path}")

    def get_desktop_path(self):
        """获取桌面路径"""
        system = os.name
        if system == 'nt':  # Windows
            return Path(os.path.expanduser("~/Desktop"))
        elif system == 'posix':  # macOS 和 Linux
            # 尝试常见的桌面路径
            possible_paths = [
                Path.home() / 'Desktop',
                Path.home() / '桌面',  # 中文系统
                Path.home() / 'Escritorio',  # 西班牙语
            ]
            for path in possible_paths:
                if path.exists():
                    return path
            return Path.home() / 'Desktop'  # 默认创建
        else:
            raise OSError("不支持的操作系统")

    def create_folders(self):
        """创建分类文件夹"""
        for category in self.file_categories.keys():
            folder_path = self.desktop_path / category
            folder_path.mkdir(exist_ok=True)
        
        # 创建其他文件夹
        others_path = self.desktop_path / self.other_folder
        others_path.mkdir(exist_ok=True)
        
        logging.info("分类文件夹创建完成")

    def organize_files(self, dry_run=False):
        """整理桌面文件
        
        Args:
            dry_run: 如果为True,只显示将要执行的操作而不实际移动文件
        """
        if not self.desktop_path.exists():
            logging.error(f"桌面路径不存在: {self.desktop_path}")
            return
        
        self.create_folders()
        
        moved_files = 0
        skipped_files = []
        
        for item in self.desktop_path.iterdir():
            # 跳过目录和系统文件
            if item.is_dir() or item.name.startswith('.') or item.name == 'desktop.ini':
                continue
            
            # 获取文件扩展名
            file_extension = item.suffix.lower()
            
            # 查找对应的分类
            target_category = None
            for category, extensions in self.file_categories.items():
                if file_extension in extensions:
                    target_category = category
                    break
            
            # 如果没有找到分类,放到Others文件夹
            if target_category is None:
                target_category = self.other_folder
            
            # 目标路径
            target_folder = self.desktop_path / target_category
            target_path = target_folder / item.name
            
            # 处理文件名冲突
            counter = 1
            original_target_path = target_path
            while target_path.exists():
                stem = original_target_path.stem
                suffix = original_target_path.suffix
                target_path = target_folder / f"{stem}_{counter}{suffix}"
                counter += 1
            
            try:
                if not dry_run:
                    # 实际移动文件
                    shutil.move(str(item), str(target_path))
                    logging.info(f"移动文件: {item.name} -> {target_category}/")
                else:
                    # 模拟运行,只显示信息
                    logging.info(f"[模拟] 移动文件: {item.name} -> {target_category}/")
                
                moved_files += 1
                
            except Exception as e:
                logging.error(f"移动文件失败 {item.name}: {str(e)}")
                skipped_files.append(item.name)
        
        # 输出整理结果
        logging.info(f"文件整理完成!")
        logging.info(f"成功移动: {moved_files} 个文件")
        if skipped_files:
            logging.warning(f"跳过文件: {len(skipped_files)} 个")
            for skipped in skipped_files:
                logging.warning(f"  - {skipped}")

    def undo_last_organization(self, backup_file='desktop_backup.txt'):
        """撤销最后一次整理(需要先运行备份功能)"""
        backup_path = self.desktop_path / backup_file
        
        if not backup_path.exists():
            logging.error("找不到备份文件,无法撤销")
            return
        
        try:
            with open(backup_path, 'r', encoding='utf-8') as f:
                for line in f:
                    original_path, current_path = line.strip().split(' -> ')
                    if Path(current_path).exists():
                        shutil.move(current_path, original_path)
                        logging.info(f"恢复: {Path(current_path).name}")
            
            # 删除备份文件
            backup_path.unlink()
            logging.info("撤销操作完成")
            
        except Exception as e:
            logging.error(f"撤销操作失败: {str(e)}")

    def create_backup_log(self):
        """创建文件移动的备份日志(用于撤销功能)"""
        backup_path = self.desktop_path / f"desktop_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        return backup_path

def main():
    """主函数"""
    print("=" * 50)
    print("           桌面文件整理小工具,开发者 黄龙江")
    print("=" * 50)
    
    try:
        # 创建整理器实例
        organizer = DesktopOrganizer()
        
        while True:
            print("\n请选择操作:")
            print("1. 整理桌面文件")
            print("2. 模拟运行(不实际移动文件)")
            print("3. 退出")
            
            choice = input("\n请输入选择 (1-3): ").strip()
            
            if choice == '1':
                print("\n开始整理桌面文件...")
                confirm = input("确定要整理吗?(y/N): ").strip().lower()
                if confirm == 'y':
                    organizer.organize_files(dry_run=False)
                else:
                    print("操作已取消")
                    
            elif choice == '2':
                print("\n开始模拟运行...")
                organizer.organize_files(dry_run=True)
                
            elif choice == '3':
                print("再见!")
                break
            else:
                print("无效的选择,请重新输入")
                
    except Exception as e:
        logging.error(f"程序运行出错: {str(e)}")
        print(f"程序运行出错,请查看日志文件获取详细信息")

if __name__ == "__main__":
    main()

额外工具:D盘快速整理脚本

# quick_organize.py - 快速整理脚本
import os
import shutil
from pathlib import Path

def quick_organize_d_drive():
    """快速整理D盘"""
    d_drive = Path("D:\\")
    
    # 简单分类
    categories = {
        '图片': ['.jpg', '.jpeg', '.png', '.gif'],
        '文档': ['.pdf', '.doc', '.docx', '.txt'],
        '压缩包': ['.zip', '.rar'],
        '软件': ['.exe', '.msi'],
        '视频': ['.mp4', '.avi'],
        '其他': []
    }
    
    # 创建文件夹
    for category in categories:
        (d_drive / category).mkdir(exist_ok=True)
    
    # 整理文件
    moved = 0
    for item in d_drive.iterdir():
        if item.is_file():
            ext = item.suffix.lower()
            target_category = '其他'
            
            for category, extensions in categories.items():
                if ext in extensions:
                    target_category = category
                    break
            
            try:
                shutil.move(str(item), str(d_drive / target_category / item.name))
                moved += 1
                print(f"移动: {item.name} -> {target_category}")
            except Exception as e:
                print(f"失败: {item.name} - {e}")
    
    print(f"\n快速整理完成! 移动了 {moved} 个文件")

if __name__ == "__main__":
    quick_organize_d_drive()

额外工具:目录快速整理小工具

import os
import shutil
import json
from pathlib import Path
from datetime import datetime
import argparse

class DynamicDirectoryOrganizer:
    def __init__(self, target_dir=None):
        """初始化动态目录整理器"""
        self.target_dir = Path(target_dir) if target_dir else Path.cwd()
        self.config_file = self.target_dir / '.directory_organizer_config.json'
        self.load_config()
        
    def load_config(self):
        """加载或创建配置文件"""
        default_categories = {
            '文档': ['.pdf', '.doc', '.docx', '.txt', '.rtf', '.md'],
            '图片': ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.svg'],
            '视频': ['.mp4', '.avi', '.mkv', '.mov', '.wmv'],
            '音频': ['.mp3', '.wav', '.flac', '.aac'],
            '压缩包': ['.zip', '.rar', '.7z', '.tar'],
            '代码': ['.py', '.java', '.js', '.html', '.css', '.cpp'],
            '数据': ['.csv', '.json', '.xml', '.xlsx'],
            '可执行文件': ['.exe', '.msi', '.bat', '.sh'],
            '其他': []
        }
        
        if self.config_file.exists():
            try:
                with open(self.config_file, 'r', encoding='utf-8') as f:
                    self.categories = json.load(f)
                print(f"已加载配置文件: {self.config_file}")
            except:
                self.categories = default_categories
                self.save_config()
        else:
            self.categories = default_categories
            self.save_config()
    
    def save_config(self):
        """保存配置到文件"""
        with open(self.config_file, 'w', encoding='utf-8') as f:
            json.dump(self.categories, f, ensure_ascii=False, indent=2)
    
    def scan_and_learn(self, auto_create_categories=True):
        """扫描目录并学习文件类型,动态创建分类"""
        print(f"扫描目录: {self.target_dir}")
        
        file_extensions = {}
        uncategorized_files = []
        
        for item in self.target_dir.iterdir():
            if item.is_file() and not item.name.startswith('.'):
                ext = item.suffix.lower()
                if ext:
                    file_extensions[ext] = file_extensions.get(ext, 0) + 1
                else:
                    uncategorized_files.append(item.name)
        
        # 动态创建新分类
        new_categories_created = False
        if auto_create_categories:
            for ext, count in file_extensions.items():
                if count >= 3:  # 同类型文件超过3个考虑创建新分类
                    category_name = self.get_category_name(ext)
                    if category_name not in self.categories and ext not in self.get_all_extensions():
                        self.categories[category_name] = [ext]
                        new_categories_created = True
                        print(f"创建新分类: {category_name} - 扩展名: {ext}")
        
        if new_categories_created:
            self.save_config()
        
        return file_extensions, uncategorized_files
    
    def get_category_name(self, extension):
        """根据扩展名生成分类名称"""
        category_names = {
            '.psd': '设计文件',
            '.ai': '矢量图',
            '.sketch': 'UI设计',
            '.fig': '设计稿',
            '.dwg': 'CAD图纸',
            '.ppt': '演示文稿',
            '.pptx': '演示文稿',
            '.epub': '电子书',
            '.mobi': '电子书',
            '.sql': '数据库',
            '.db': '数据库文件',
            '.iso': '镜像文件',
            '.torrent': '种子文件',
            '.apk': '安卓应用',
            '.dmg': 'Mac应用',
            '.ttf': '字体文件',
            '.otf': '字体文件'
        }
        
        return category_names.get(extension, f"{extension[1:].upper()}文件")
    
    def get_all_extensions(self):
        """获取所有已分类的扩展名"""
        all_extensions = []
        for extensions in self.categories.values():
            all_extensions.extend(extensions)
        return all_extensions
    
    def organize_files(self, dry_run=False, move_other_files=True):
        """整理文件"""
        print(f"{'[模拟运行] ' if dry_run else ''}开始整理文件...")
        
        # 先扫描学习
        file_extensions, uncategorized_files = self.scan_and_learn()
        
        # 创建分类文件夹
        for category in self.categories:
            category_path = self.target_dir / category
            if not dry_run:
                category_path.mkdir(exist_ok=True)
        
        moved_files = []
        skipped_files = []
        
        for item in self.target_dir.iterdir():
            # 跳过目录、隐藏文件和配置文件
            if (item.is_dir() or 
                item.name.startswith('.') or 
                item.name == self.config_file.name):
                continue
            
            try:
                file_category = self.categorize_file(item)
                if file_category or move_other_files:
                    target_category = file_category if file_category else '其他'
                    target_dir = self.target_dir / target_category
                    
                    # 处理文件名冲突
                    target_path = self.get_unique_path(target_dir, item.name)
                    
                    if not dry_run:
                        shutil.move(str(item), str(target_path))
                    
                    moved_files.append({
                        'file': item.name,
                        'from': str(item.parent),
                        'to': str(target_dir),
                        'category': target_category
                    })
                    
                    status = "移动" if not dry_run else "将移动"
                    print(f"{status}: {item.name} -> {target_category}/")
                
                else:
                    skipped_files.append(item.name)
                    print(f"跳过: {item.name} (未分类)")
                    
            except Exception as e:
                print(f"错误处理文件 {item.name}: {e}")
                skipped_files.append(item.name)
        
        # 生成报告
        self.generate_report(moved_files, skipped_files, dry_run)
        
        return moved_files, skipped_files
    
    def categorize_file(self, file_path):
        """分类单个文件"""
        ext = file_path.suffix.lower()
        
        for category, extensions in self.categories.items():
            if ext in extensions:
                return category
        
        return None
    
    def get_unique_path(self, directory, filename):
        """生成唯一文件路径,避免名称冲突"""
        path = directory / filename
        if not path.exists():
            return path
        
        name_parts = path.stem, path.suffix
        counter = 1
        while True:
            new_name = f"{name_parts[0]}_{counter}{name_parts[1]}"
            new_path = directory / new_name
            if not new_path.exists():
                return new_path
            counter += 1
    
    def generate_report(self, moved_files, skipped_files, dry_run):
        """生成整理报告"""
        report_file = self.target_dir / f"整理报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
        
        with open(report_file, 'w', encoding='utf-8') as f:
            f.write("文件整理报告\n")
            f.write("=" * 50 + "\n")
            f.write(f"整理时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
            f.write(f"整理目录: {self.target_dir}\n")
            f.write(f"模式: {'模拟运行' if dry_run else '实际整理'}\n\n")
            
            f.write(f"移动文件: {len(moved_files)} 个\n")
            f.write(f"跳过文件: {len(skipped_files)} 个\n\n")
            
            # 按分类统计
            category_stats = {}
            for move in moved_files:
                category = move['category']
                category_stats[category] = category_stats.get(category, 0) + 1
            
            f.write("按分类统计:\n")
            for category, count in sorted(category_stats.items()):
                f.write(f"  {category}: {count} 个文件\n")
            
            f.write("\n移动详情:\n")
            for move in moved_files:
                f.write(f"  {move['file']} -> {move['category']}/\n")
            
            if skipped_files:
                f.write("\n跳过的文件:\n")
                for skipped in skipped_files:
                    f.write(f"  {skipped}\n")
        
        print(f"整理报告已保存: {report_file}")
    
    def show_categories(self):
        """显示当前分类配置"""
        print("\n当前分类配置:")
        print("-" * 40)
        for category, extensions in self.categories.items():
            print(f"{category}: {', '.join(extensions) if extensions else '其他文件'}")
    
    def add_category(self, category_name, extensions):
        """添加新分类"""
        if category_name in self.categories:
            print(f"分类 '{category_name}' 已存在!")
            return False
        
        self.categories[category_name] = extensions
        self.save_config()
        print(f"成功添加分类: {category_name} - 扩展名: {extensions}")
        return True
    
    def remove_category(self, category_name):
        """移除分类"""
        if category_name not in self.categories:
            print(f"分类 '{category_name}' 不存在!")
            return False
        
        if category_name == '其他':
            print("不能删除'其他'分类!")
            return False
        
        del self.categories[category_name]
        self.save_config()
        print(f"成功删除分类: {category_name}")
        return True

def main():
    """命令行主函数"""
    parser = argparse.ArgumentParser(description='动态目录快速整理工具')
    parser.add_argument('directory', nargs='?', default='.', help='要整理的目录路径(默认为当前目录)')
    parser.add_argument('--dry-run', action='store_true', help='模拟运行,不实际移动文件')
    parser.add_argument('--scan', action='store_true', help='仅扫描目录,学习文件类型')
    parser.add_argument('--show-categories', action='store_true', help='显示当前分类配置')
    parser.add_argument('--add-category', nargs=2, metavar=('NAME', 'EXTENSIONS'), 
                       help='添加新分类,例如: --add-category 设计文件 ".psd,.ai"')
    parser.add_argument('--remove-category', help='移除指定分类')
    
    args = parser.parse_args()
    
    organizer = DynamicDirectoryOrganizer(args.directory)
    
    if args.scan:
        file_extensions, uncategorized = organizer.scan_and_learn()
        print(f"\n发现 {len(file_extensions)} 种文件扩展名:")
        for ext, count in sorted(file_extensions.items(), key=lambda x: x[1], reverse=True):
            print(f"  {ext}: {count} 个文件")
        
        if uncategorized:
            print(f"\n无扩展名文件: {len(uncategorized)} 个")
            for file in uncategorized[:10]:  # 只显示前10个
                print(f"  {file}")
    
    elif args.show_categories:
        organizer.show_categories()
    
    elif args.add_category:
        category_name = args.add_category[0]
        extensions = [ext.strip() for ext in args.add_category[1].split(',')]
        organizer.add_category(category_name, extensions)
    
    elif args.remove_category:
        organizer.remove_category(args.remove_category)
    
    else:
        organizer.organize_files(dry_run=args.dry_run)

if __name__ == "__main__":
    # 交互式模式
    if len(os.sys.argv) == 1:
        print("动态目录快速整理工具")
        print("=" * 40)
        
        target_dir = input("请输入要整理的目录路径 (回车使用当前目录): ").strip()
        target_dir = target_dir if target_dir else "."
        
        organizer = DynamicDirectoryOrganizer(target_dir)
        
        while True:
            print(f"\n当前目录: {organizer.target_dir}")
            print("请选择操作:")
            print("1. 扫描目录并显示文件统计")
            print("2. 模拟运行整理")
            print("3. 实际整理文件")
            print("4. 显示分类配置")
            print("5. 添加新分类")
            print("6. 删除分类")
            print("7. 退出")
            
            choice = input("\n请输入选择 (1-7): ").strip()
            
            if choice == '1':
                file_extensions, uncategorized = organizer.scan_and_learn()
                print(f"\n文件统计:")
                for ext, count in sorted(file_extensions.items(), key=lambda x: x[1], reverse=True)[:15]:
                    print(f"  {ext}: {count} 个文件")
            
            elif choice == '2':
                organizer.organize_files(dry_run=True)
            
            elif choice == '3':
                confirm = input("确定要整理文件吗?(y/N): ").lower()
                if confirm == 'y':
                    organizer.organize_files(dry_run=False)
            
            elif choice == '4':
                organizer.show_categories()
            
            elif choice == '5':
                name = input("请输入分类名称: ").strip()
                exts = input("请输入扩展名(用逗号分隔,如 .psd,.ai): ").strip()
                extensions = [ext.strip() for ext in exts.split(',')]
                organizer.add_category(name, extensions)
            
            elif choice == '6':
                name = input("请输入要删除的分类名称: ").strip()
                organizer.remove_category(name)
            
            elif choice == '7':
                print("再见!")
                break
            
            else:
                print("无效选择!")
    else:
        main()
当前文章内容为原创转载请注明出处:http://www.good1230.com/detail/2025-09-23/879.html
最后生成于 2025-09-23 09:02:07
此内容有帮助 ?
0