该段代码使用与windows与Linux,同时可以学习time的相关操作,以及time的格式转换 # coding:utf-8 import os import time import shutil # %Y Year with century as a decimal number. # %m Month as a decimal number [01,12]. # %d Day of the month as a decimal number [01,31]. # %H Hour (24-hour clock) as a decimal number [00,23]. # %M Minute as a decimal number [00,59]. # %S Second as a decimal number [00,61]. # %z Time zone offset from UTC. # %a Locale's abbreviated weekday name. # %A Locale's full weekday name. # %b Locale's abbreviated month name. # %B Locale's full month name. # %c Locale's appropriate date and time representation. # %I Hour (12-hour clock) as a decimal number [01,12]. # %p Locale's equivalent of either AM or PM. # Thu Jan 28 14:03:39 2021 def remove_file_detail(path, diff_time): # path D:\Package\test1\cc.txt ctime = time.ctime(os.stat(path).st_ctime) # 获取文件创建时间 time of last change atime = time.ctime(os.stat(path).st_atime) # 获取文件创建时间 time of last access mtime = time.ctime(os.stat(path).st_mtime) # 获取文件创建时间 time of last modification # print(ctime) #Tue Jan 26 17:39:04 2021 timestring = time.strptime(ctime, "%a %b %d %H:%M:%S %Y") # 根据ctime的输出格式写出format字符串格式 # print(timestring) #time.struct_time(tm_year=2021, tm_mon=1, tm_mday=28, tm_hour=14, tm_min=3, tm_sec=45, tm_wday=3, tm_yday=28, tm_isdst=-1) timemiao = time.mktime(timestring) # 将时间班变成秒数 # print(timemiao) #1611653944.0 now = time.time() # 获取当前时间的秒 # print(now) #1611814750.68371 diff = now - timemiao # 当前时间的秒数和文件创建时候想对比 # print(diff) # 如果创建时间大于diff_time,删除该文件 if diff > diff_time: print("delete the file: ", path) # path = D:\Package\test1\re1.txt if os.path.exists(path): if os.path.isfile(): os.remove(path) elif os.path.isdir(path): shutil.rmtree(path) # 删除当前文件夹下所有文件和和子文件夹 def remove_file(): path = r"D:\Package\test1" items = os.listdir(path) # print(items) for n in items: p = path + "\\" + n print(p) diff_time = 60 * 60 * 24 * 7 * 365 #根据自己需求定义时间间隔,这里定义是一年 remove_file_detail(p, diff_time) if __name__ == '__main__': remove_file()
Python删除文件夹中旧文件
最新推荐文章于 2024-02-19 14:38:49 发布