以下是一个Python脚本示例,可以用来将昨天创建的文件移动到对应的月份文件夹中,并在每个月的最后一天进行压缩:

import os
import shutil
import datetime
import zipfile

# 获取昨天的日期
yesterday = datetime.date.today() - datetime.timedelta(days=1)

# 获取昨天创建的文件
files = [f for f in os.listdir('.') if os.path.isfile(f) and os.path.getctime(f) > yesterday.timestamp()]

# 创建月份文件夹
month_folder = yesterday.strftime('%Y-%m')
if not os.path.exists(month_folder):
    os.makedirs(month_folder)

# 移动文件到月份文件夹中
for file in files:
    shutil.move(file, os.path.join(month_folder, file))

# 获取当前日期
today = datetime.date.today()

# 判断是否为月份的最后一天
if today.day == datetime.date(today.year, today.month, 1).replace(day=28).day:
    # 压缩月份文件夹
    zip_name = month_folder + '.zip'
    with zipfile.ZipFile(zip_name, 'w') as zipf:
        for root, dirs, files in os.walk(month_folder):
            for file in files:
                zipf.write(os.path.join(root, file), file)
    
    # 删除月份文件夹
    shutil.rmtree(month_folder)

请注意,以上代码假设脚本文件与要处理的文件在同一个目录中。如果文件不在同一个目录中,你需要在以下代码行中提供文件的路径:

files = [f for f in os.listdir('文件路径') if os.path.isfile(os.path.join('文件路径', f)) and os.path.getctime(os.path.join('文件路径', f)) > yesterday.timestamp()]

并且,在以下代码行中提供月份文件夹的路径:

month_folder = os.path.join('文件路径', yesterday.strftime('%Y-%m'))

希望这可以帮助到你!

用python脚本把昨天创建的文件移动到月份文件夹中每月最后一天进行压缩

原文地址: https://www.cveoy.top/t/topic/i9cu 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录