Python案例如何批量移动文件?

wen python案例 59

本文目录导读:

Python案例如何批量移动文件?

  1. 方法一:使用shutil模块(最常用)
  2. 方法二:使用pathlib(现代Python推荐)
  3. 方法三:带进度显示
  4. 方法四:按文件类型分类移动
  5. 方法五:按日期移动文件
  6. 实用示例:移动特定大小的文件
  7. 注意事项

我来介绍几种Python批量移动文件的方法。

使用shutil模块(最常用)

import shutil
import os
from pathlib import Path
def batch_move_files(src_dir, dst_dir, file_extensions=None):
    """
    批量移动文件
    参数:
        src_dir: 源目录
        dst_dir: 目标目录
        file_extensions: 要移动的文件扩展名列表,如['.txt', '.jpg']
    """
    # 确保目标目录存在
    Path(dst_dir).mkdir(parents=True, exist_ok=True)
    # 遍历源目录
    for filename in os.listdir(src_dir):
        src_path = os.path.join(src_dir, filename)
        dst_path = os.path.join(dst_dir, filename)
        # 只处理文件,不处理目录
        if os.path.isfile(src_path):
            # 如果指定了扩展名过滤
            if file_extensions:
                ext = os.path.splitext(filename)[1].lower()
                if ext not in file_extensions:
                    continue
            try:
                shutil.move(src_path, dst_path)
                print(f"已移动: {filename}")
            except Exception as e:
                print(f"移动失败 {filename}: {e}")
# 使用示例
batch_move_files('./source', './destination', ['.txt', '.pdf'])

使用pathlib(现代Python推荐)

from pathlib import Path
import shutil
def batch_move_files_pathlib(src_dir, dst_dir, pattern="*"):
    """
    使用pathlib批量移动文件
    参数:
        src_dir: 源目录
        dst_dir: 目标目录
        pattern: 文件匹配模式,如"*.txt", "*2024*"
    """
    src_path = Path(src_dir)
    dst_path = Path(dst_dir)
    # 创建目标目录
    dst_path.mkdir(parents=True, exist_ok=True)
    # 遍历匹配的文件
    for file_path in src_path.glob(pattern):
        if file_path.is_file():
            try:
                shutil.move(str(file_path), str(dst_path / file_path.name))
                print(f"已移动: {file_path.name}")
            except Exception as e:
                print(f"移动失败 {file_path.name}: {e}")
# 使用示例
batch_move_files_pathlib('./source', './destination', "*.jpg")

带进度显示

import shutil
import os
from pathlib import Path
from tqdm import tqdm  # 需要安装: pip install tqdm
def batch_move_with_progress(src_dir, dst_dir, file_types=None):
    """
    带进度条批量移动文件
    """
    src_path = Path(src_dir)
    dst_path = Path(dst_dir)
    dst_path.mkdir(parents=True, exist_ok=True)
    # 获取所有文件
    files = [f for f in src_path.iterdir() if f.is_file()]
    # 过滤文件类型
    if file_types:
        files = [f for f in files if f.suffix.lower() in file_types]
    # 带进度条移动
    for file_path in tqdm(files, desc="移动文件中"):
        try:
            shutil.move(str(file_path), str(dst_path / file_path.name))
        except Exception as e:
            print(f"\n移动失败 {file_path.name}: {e}")
# 使用示例
batch_move_with_progress('./source', './destination', ['.png', '.jpg'])

按文件类型分类移动

import shutil
import os
from pathlib import Path
def move_files_by_type(src_dir, dst_base_dir):
    """
    按文件类型分类移动到不同文件夹
    """
    src_path = Path(src_dir)
    # 文件类型分类规则
    type_folders = {
        '.txt': 'text_files',
        '.pdf': 'pdf_files',
        '.jpg': 'image_files',
        '.png': 'image_files',
        '.docx': 'word_files',
        '.xlsx': 'excel_files',
        '.mp4': 'video_files',
        '.mp3': 'audio_files',
    }
    for file_path in src_path.iterdir():
        if file_path.is_file():
            # 获取文件扩展名
            ext = file_path.suffix.lower()
            # 确定目标文件夹
            folder_name = type_folders.get(ext, 'other_files')
            dst_path = Path(dst_base_dir) / folder_name
            # 创建目标文件夹
            dst_path.mkdir(parents=True, exist_ok=True)
            try:
                shutil.move(str(file_path), str(dst_path / file_path.name))
                print(f"已移动 {file_path.name} -> {folder_name}")
            except Exception as e:
                print(f"移动失败 {file_path.name}: {e}")
# 使用示例
move_files_by_type('./downloads', './sorted_files')

按日期移动文件

import shutil
import os
from pathlib import Path
from datetime import datetime
def move_files_by_date(src_dir, dst_base_dir):
    """
    按文件创建日期移动文件
    格式: YYYY/MM/DD
    """
    src_path = Path(src_dir)
    for file_path in src_path.iterdir():
        if file_path.is_file():
            # 获取文件修改时间
            mtime = os.path.getmtime(file_path)
            date = datetime.fromtimestamp(mtime)
            # 创建按日期组织的路径:YYYY/MM/DD
            date_path = Path(str(date.year)) / str(date.month).zfill(2) / str(date.day).zfill(2)
            dst_path = Path(dst_base_dir) / date_path
            # 创建目录
            dst_path.mkdir(parents=True, exist_ok=True)
            try:
                shutil.move(str(file_path), str(dst_path / file_path.name))
                print(f"已移动 {file_path.name} -> {date_path}")
            except Exception as e:
                print(f"移动失败 {file_path.name}: {e}")
# 使用示例
move_files_by_date('./photos', './organized_photos')

实用示例:移动特定大小的文件

import shutil
import os
from pathlib import Path
def move_large_files(src_dir, dst_dir, max_size_mb=10):
    """
    移动大于指定大小的文件
    """
    src_path = Path(src_dir)
    dst_path = Path(dst_dir)
    dst_path.mkdir(parents=True, exist_ok=True)
    max_size_bytes = max_size_mb * 1024 * 1024
    for file_path in src_path.iterdir():
        if file_path.is_file():
            file_size = file_path.stat().st_size
            if file_size > max_size_bytes:
                try:
                    shutil.move(str(file_path), str(dst_path / file_path.name))
                    size_mb = file_size / (1024 * 1024)
                    print(f"已移动大文件: {file_path.name} ({size_mb:.2f} MB)")
                except Exception as e:
                    print(f"移动失败 {file_path.name}: {e}")
# 使用示例
move_large_files('./downloads', './large_files', max_size_mb=100)

注意事项

  1. 备份重要数据:移动操作不可逆,建议先测试
  2. 错误处理:添加异常处理,避免程序中断
  3. 文件冲突:可使用os.path.exists()检查目标文件是否存在
  4. 权限问题:确保有足够的文件操作权限

这些方法可以根据你的具体需求选择和修改,需要我详细解释某个方法或帮您针对特定场景优化代码吗?

抱歉,评论功能暂时关闭!