text_del.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import os
  2. import time
  3. import datetime
  4. import shutil
  5. from apscheduler.schedulers.blocking import BlockingScheduler
  6. path = r'D:\zwj\word_uploads'
  7. def del_flie():
  8. # 获取文件夹下所有文件和文件夹
  9. files = os.listdir(path)
  10. files.sort(key=lambda x: int(x)) # 从小到大排列
  11. print(files)
  12. tody_time = datetime.datetime.now().date().strftime('%Y-%m-%d')
  13. before_10_days = (datetime.datetime.now() + datetime.timedelta(days=-10)).date().strftime('%Y-%m-%d')
  14. for file in files:
  15. file_path = os.path.join(path, file)
  16. # 文件最后一次修改的时间
  17. file_time = time.strftime('%Y-%m-%d', time.localtime(os.stat(file_path).st_mtime))
  18. # 判断是否是文件,这里直接删除文件夹就可以了
  19. if file_time < before_10_days: # 比较时间即可,保留10天的文件
  20. if os.path.isfile(file_path):
  21. # print('phy_uploads的子文件中存在文件', file, '-----',file_time)
  22. # 删除过期文件
  23. os.remove(file_path)
  24. elif os.path.isdir(file_path): # 如果是文件夹,继续遍历删除
  25. shutil.rmtree(file_path) # 递归删除文件夹,会把phy_uploads整个文件夹都给删了
  26. print(file_path + " was removed!")
  27. # def dojob():
  28. # # 创建调度器:BlockingScheduler
  29. # scheduler = BlockingScheduler()
  30. # now_time = str(datetime.datetime.now().time())[:2]
  31. # while True:
  32. # if int(now_time) >= 13 or int(now_time) <= 5:
  33. # # 添加任务,时间间隔7天
  34. # scheduler.add_job(del_flie, 'interval', days=7) # 阻塞方式,每隔7days执行一次,刚启动时不执行
  35. # scheduler.start()
  36. def dojob():
  37. # 创建调度器:BlockingScheduler
  38. scheduler = BlockingScheduler()
  39. # 添加任务,时间间隔7天
  40. scheduler.add_job(del_flie, 'interval', days=7, start_date='2020-11-01 01:00:00') # 阻塞方式,每隔7days执行一次,刚启动时不执行
  41. # scheduler.add_job(del_flie, "cron", day_of_week = "7", hour = 1, minute = 0)
  42. scheduler.start()
  43. if __name__ == '__main__':
  44. print("\n--------delete file process is start--------\n")
  45. dojob()