You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python脚本以选取过去12个月内的目标文件夹?

解决方案

核心思路

要获取过去12个月的文件夹内容,关键是逐个生成近12个月的「年-月」格式字符串,再依次遍历每个对应路径下的文件。借助datetime模块处理日期推移,能自动规避跨年、跨月的边界问题(比如从2024-01往前推1个月直接得到2023-12)。

修改后的代码示例(推荐)

import os
from datetime import datetime
from dateutil.relativedelta import relativedelta  # 需先安装:pip install python-dateutil

# 抽离固定基础路径,后续修改更便捷
base_path = r"F:\6 - Business Units\Sun Pacific Farming Cooperative\B - General\17 - GIS\Drone Imagery\RBG\Monthly"

today = datetime.now()

# 遍历过去12个月(包含当前月)
for i in range(12):
    # 计算目标月份的日期
    target_date = today - relativedelta(months=i)
    # 生成「年-月」格式的文件夹名
    folder_name = target_date.strftime("%Y-%m")
    # 拼接完整文件夹路径
    folder_path = os.path.join(base_path, folder_name)
    
    # 先检查文件夹是否存在,避免新增不及时导致报错
    if os.path.exists(folder_path):
        # 获取文件夹内所有文件
        files = os.listdir(folder_path)
        print(f"===== {folder_name} 下的文件 =====")
        for file in files:
            # 这里可替换为你的实际操作(比如复制、读取文件)
            print(os.path.join(folder_path, file))
    else:
        print(f"文件夹 {folder_path} 不存在,跳过")

无额外依赖的替代方案

如果不想安装python-dateutil,可以用datetime的原生方法手动计算年月:

import os
from datetime import datetime

base_path = r"F:\6 - Business Units\Sun Pacific Farming Cooperative\B - General\17 - GIS\Drone Imagery\RBG\Monthly"
today = datetime.now()

for i in range(12):
    year = today.year
    month = today.month - i
    # 处理月份小于1的跨年情况
    while month < 1:
        year -= 1
        month += 12
    # 确保月份是两位数格式(比如5转为05)
    folder_name = f"{year}-{month:02d}"
    folder_path = os.path.join(base_path, folder_name)
    
    if os.path.exists(folder_path):
        files = os.listdir(folder_path)
        print(f"===== {folder_name} 下的文件 =====")
        for file in files:
            print(os.path.join(folder_path, file))

内容的提问来源于stack exchange,提问作者George Bunkall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 01:14:54