python将指定目录下指定年限以前的所有文件转移到指定的目录

常用各类软硬件使用技巧、疑难、最新资讯等相关交流
回复
rungod
帖子: 62
注册时间: 2010-06-19 3:51

python将指定目录下指定年限以前的所有文件转移到指定的目录

帖子 rungod »

代码: 全选

import os
import shutil
import time

def move_old_files(source_dir, target_dir, years=2):
    """
    将 source_dir 中超过指定年份的文件(含子目录)剪切到 target_dir
    :param source_dir: 源目录路径
    :param target_dir: 目标目录路径
    :param years: 年份阈值,默认为2年
    """
    # 计算两年前的时间戳
    current_time = time.time()
    threshold_time = current_time - (years * 365 * 24 * 60 * 60)

    moved_count = 0
    for root, dirs, files in os.walk(source_dir):
        for file in files:
            file_path = os.path.join(root, file)
            
            # 获取文件的最后修改时间
            try:
                file_mtime = os.path.getmtime(file_path)
            except OSError:
                continue  # 如果无法获取文件时间,跳过

            # 判断文件是否早于两年前的时间点
            if file_mtime < threshold_time:
                # 计算相对路径,以便在目标目录中重建相同的子目录结构
                relative_path = os.path.relpath(file_path, source_dir)
                target_file_path = os.path.join(target_dir, relative_path)
                
                # 确保目标子目录存在
                target_sub_dir = os.path.dirname(target_file_path)
                if not os.path.exists(target_sub_dir):
                    os.makedirs(target_sub_dir)

                # 执行剪切(移动)操作
                try:
                    shutil.move(file_path, target_file_path)
                    moved_count += 1
                    print(f"已移动: {relative_path}")
                except Exception as e:
                    print(f"移动失败: {relative_path}, 错误: {e}")

    print(f"\n操作完成!共移动了 {moved_count} 个文件到 {target_dir}")

# --- 使用示例 ---
if __name__ == "__main__":
    # 1. 修改为你需要处理的源目录
    source_directory = r"C:\path\to\your\source\folder"
    # 2. 修改为你想要移动到的目标目录
    target_directory = r"C:\path\to\your\target\folder"

    if not os.path.exists(source_directory):
        print("错误:源目录不存在,请检查路径!")
    else:
        move_old_files(source_directory, target_directory)
心海质水
回复