首页 > 代码库 > 删除windows上特定目录下以*.rar后缀名的python脚本

删除windows上特定目录下以*.rar后缀名的python脚本

import os,fnmatch,datetime,time
def all_files(root,pattern=‘*‘,single_level=False,yield_folders=False):
    patterns = pattern.split(‘;‘)
    for path,subirs,files in os.walk(root):
        if yield_folders:
            files.extend(subirs)
        files.sort()

        for name in files:
            for pattern in patterns:
                if fnmatch.fnmatch(name,pattern):
                    yield os.path.join(path,name)
                    break
        if single_level:
            break
for path in all_files("E:/",‘*.rar‘):
    print(path)
    create_file_time = os.path.getatime(path) #文件创建的时间戳
    ltime = time.localtime(create_file_time)
    timestr = time.strftime("%Y-%m-%d %H:%M:%S",ltime)  #验证时间戳转换为年月日格式,测试用
    print(timestr)
    age_in_days = ((time.time()-create_file_time)/(60*60*24))
    if age_in_days > 20:
        os.remove(path)
        print(‘remove file: %s‘ % path)
    else:
        print("文件创建天数小于20天")

  

脚本的作用是,删除d盘下日期为20天前的rar文件,这些rar在不同的目录下。

参考:http://www.iplaypy.com/sys/s104.html

删除windows上特定目录下以*.rar后缀名的python脚本