# coding=utf-8 import os import time import sys import shutil PATH = sys.argv[1] MAX_DAY = sys.argv[2] # 获取指定路径下的所有文件信息,并返回一个绝对路径的列表 def get_files(path): if os.path.exists(path): files = os.listdir(r"%s" % path) abs_path_list = [] for file in files: try: filepath = os.path.join(os.path.abspath(path), file) abs_path_list.append(filepath) except Exception as e: print(e) return abs_path_list else: print('路径不存在') # 传入路径,指定删除的天数前 def mtime_ge_day(filepath, day): if os.path.exists(filepath): if time.time() - os.path.getmtime(filepath) > 86400 * int(day): # 当前时间 - 文件修改时间 > 天 if os.path.isdir(filepath): shutil.rmtree(filepath) print('文件夹:%s 删除成功' % filepath) else: os.remove(filepath) print('文件:%s 删除成功' % filepath) else: return else: return if __name__ == '__main__': file_path_list = get_files(PATH) for filepath in file_path_list: mtime_ge_day(filepath, MAX_DAY)
执行效果如下:
删除D:\DCBrowserDownloads\SanGuoZhanJiQuanJi_chs_setup\game
下修改时间大于10天的数据:
python rm_ge_day.py "D:\DCBrowserDownloads\SanGuoZhanJiQuanJi_chs_setup\game" 10
注:os.removedirs(path)递归删除目录,只能删除空目录,所以使用shutil.rmtree进行删除