Python实现定时截屏并自动清理旧文件的方案

沿途有光
沿途有光
发布时间:2026-10-13 | 3人浏览过
原创

本文提供Python实现屏幕截取并保存为文件的完整代码,利用PIL库获取图像,结合schedule库设定周期性截屏与定时清理任务。代码演示如何按日期创建目录保存截图,并自动删除指定天数前的旧截图目录,适用于需要定期监控屏幕状态的场景。

Python截屏与自动清理实现代码

这里直接展示核心实现代码,无需过多解释。


from PIL import ImageGrab
import time
import schedule
import os
import shutil
import datetime

days = -3
# 截屏
def savepic():
 im = ImageGrab.grab()
 now = time.strftime("%Y_%m_%d_%H_%M_%S", time.localtime())
 day = time.strftime("%Y%m%d", time.localtime())
 file_path_top = 'c:\\tmp\\'
 if not os.path.exists(file_path_top):
  os.mkdir(file_path_top)
 file_path = 'c:\\tmp\\'+day+'\\'
 if not os.path.exists(file_path):
  os.mkdir(file_path)
 im.save(file_path+now+'.jpg')

# 删除文件
def deletefile(): 
 today = datetime.datetime.now()
 offset = datetime.timedelta(days=days)
 re_date = today + offset
 file_dir = r'C:\tmp'
 for root, dirs, files in os.walk(file_dir):
  for i in dirs:
   if(i<=re_date.strftime('%Y%m%d')):
    path = 'C:\\tmp\\'+i
    if (os.path.exists(path)):
     shutil.rmtree(path)
         
schedule.every(60).seconds.do(savepic)
schedule.every().day.at("00:30").do(deletefile)
while True:
  schedule.run_pending()
  time.sleep(1)

上述Python代码展示了如何截屏保存及清理过期文件,供读者参考使用。

相关标签:

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表