使用简单的python代码进行文件的分类与移动

部署运行你感兴趣的模型镜像

概述

Python提供了多种灵活的方法来进行智能化的文件移动与分类管理,其中可以使用shutil和os模块来根据文件的扩展名、关键词、日期进行文件的移动与分类。以下是一些常见的方法和示例。

代码示例实现

基本文件移动

import shutil
import os

# 移动单个文件
def move_file(source_path, destination_path):
    try:
        shutil.move(source_path, destination_path)
        print(f"文件已移动: {source_path} -> {destination_path}")
    except Exception as e:
        print(f"移动文件时出错: {e}")

# 示例
source = "path/to/source/file.txt"
destination = "path/to/destination/file.txt"
move_file(source, destination)

根据扩展名分类文件

import os
import shutil
from pathlib import Path

def classify_by_extension(source_dir, target_dir):
    """
    根据文件扩展名分类文件
    """
    # 确保目标目录存在
    Path(target_dir).mkdir(parents=True, exist_ok=True)
    
    for filename in os.listdir(source_dir):
        source_path = os.path.join(source_dir, filename)
        
        # 跳过目录,只处理文件
        if os.path.isfile(source_path):
            # 获取文件扩展名(去掉点)
            extension = Path(filename).suffix[1:].lower()  # 转为小写
            
            if extension:  # 如果有扩展名
                # 创建扩展名子目录
                ext_dir = os.path.join(target_dir, extension)
                Path(ext_dir).mkdir(parents=True, exist_ok=True)
                
                # 移动文件
                destination_path = os.path.join(ext_dir, filename)
                shutil.move(source_path, destination_path)
                print(f"已移动: {filename} -> {ext_dir}/")
            else:
                print(f"跳过无扩展名文件: {filename}")

# 示例使用
classify_by_extension("path/to/source", "path/to/destination")

根据关键词分类文件

import os
import shutil
from pathlib import Path

def classify_by_keywords(source_dir, target_dir, keyword_categories):
    """
    根据文件名中的关键词分类文件
    keyword_categories: 字典,键为分类名,值为关键词列表
    """
    Path(target_dir).mkdir(parents=True, exist_ok=True)
    
    for filename in os.listdir(source_dir):
        source_path = os.path.join(source_dir, filename)
        
        if os.path.isfile(source_path):
            file_moved = False
            
            for category, keywords in keyword_categories.items():
                # 检查文件名是否包含该类别的任何关键词
                if any(keyword.lower() in filename.lower() for keyword in keywords):
                    # 创建分类目录
                    category_dir = os.path.join(target_dir, category)
                    Path(category_dir).mkdir(parents=True, exist_ok=True)
                    
                    # 移动文件
                    destination_path = os.path.join(category_dir, filename)
                    shutil.move(source_path, destination_path)
                    print(f"已移动: {filename} -> {category}/")
                    file_moved = True
                    break
            
            if not file_moved:
                # 如果没有匹配任何分类,移动到"其他"目录
                other_dir = os.path.join(target_dir, "其他")
                Path(other_dir).mkdir(parents=True, exist_ok=True)
                destination_path = os.path.join(other_dir, filename)
                shutil.move(source_path, destination_path)
                print(f"已移动: {filename} -> 其他/")

# 示例使用
keyword_categories = {
    "图片": ["photo", "image", "pic", "截图"],
    "文档": ["doc", "report", "论文", "文档"],
    "代码": ["code", "program", "script", "python"],
    "视频": ["video", "movie", "录像"]
}

classify_by_keywords("path/to/source", "path/to/destination", keyword_categories)

根据日期分类文件

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

def classify_by_date(source_dir, target_dir, date_format="%Y-%m"):
    """
    根据文件修改日期分类文件
    date_format: 日期格式,如 "%Y"(年)、"%Y-%m"(年月)、"%Y-%m-%d"(年月日)
    """
    Path(target_dir).mkdir(parents=True, exist_ok=True)
    
    for filename in os.listdir(source_dir):
        source_path = os.path.join(source_dir, filename)
        
        if os.path.isfile(source_path):
            # 获取文件修改时间
            modify_time = os.path.getmtime(source_path)
            date_str = datetime.fromtimestamp(modify_time).strftime(date_format)
            
            # 创建日期目录
            date_dir = os.path.join(target_dir, date_str)
            Path(date_dir).mkdir(parents=True, exist_ok=True)
            
            # 移动文件
            destination_path = os.path.join(date_dir, filename)
            shutil.move(source_path, destination_path)
            print(f"已移动: {filename} -> {date_str}/")

# 示例使用
classify_by_date("path/to/source", "path/to/destination", "%Y-%m")  # 按年月分类

安全移动函数(避免覆盖)

import os
import shutil
from pathlib import Path

def safe_move_file(source_path, destination_dir, filename=None):
    """
    安全移动文件,避免文件名冲突
    """
    if filename is None:
        filename = os.path.basename(source_path)
    
    destination_path = os.path.join(destination_dir, filename)
    
    # 如果目标文件已存在,在文件名后添加数字
    counter = 1
    name, ext = os.path.splitext(filename)
    
    while os.path.exists(destination_path):
        new_filename = f"{name}_{counter}{ext}"
        destination_path = os.path.join(destination_dir, new_filename)
        counter += 1
    
    shutil.move(source_path, destination_path)
    return destination_path

注意事项

  1. 备份数据:在运行文件移动操作前,最好先备份重要文件
  2. 权限问题:确保有足够的权限读写相关目录
  3. 路径处理:使用os.path.join()来处理路径,避免跨平台兼容性
  4. 问题异常处理:添加适当的异常处理来应对各种错误情况

这些函数可以根据你的具体需求进行修改和组合使用,实现灵活的文件分类和移动功能。

您可能感兴趣的与本文相关的镜像

Python3.9

Python3.9

Conda
Python

Python 是一种高级、解释型、通用的编程语言,以其简洁易读的语法而闻名,适用于广泛的应用,包括Web开发、数据分析、人工智能和自动化脚本

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小明在码代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值