根据修改时间,删除文件夹。
例如:删除某个日期之前的文件夹。
# -*- coding: utf-8 -*-
# @Time : 2023/1/9 19:34
# @Author : King
# @Software: PyCharm
# @Describe:
# -*- encoding:utf-8 -*-
import os
import time
import shutil
class Folder:
def __init__(self, name, createTime, delFlag):
self.name = name
self.createTime = createTime
self.delFlag = delFlag
def TimeStampToTime(timestamp):
timeStruct = time.localtime(timestamp)
return time.strftime('%Y-%m-%d %H:%M:%S', timeStruct)
def get_FileCreateTime(filePath):
# '''获取文件的创建时间'''
# filePath = unicode(filePath,'utf8')
t = os.path.getctime(filePath)
return TimeStampToTime(t)
def get_FileModifyTime(filePath):
# '''获取文件的修改时间'''
# filePath = unicode(filePath, 'utf8')
t = os.path.getmtime(filePath)
return TimeStampToTime(t)
def get_FileAccessTime(filePath):
# '''获取文件的访问时间'''
# filePath = unicode(filePath, 'utf8')
t = os.path.getatime(filePath)
return TimeStampToTime(t)
def get_FileSize(filePath):
# '''获取文件的大小,结果保留两位小数,单位为MB'''
# filePath = unicode(filePath,'utf8')
fsize = os.path.getsize(filePath)
fsize = fsize / float(1024 * 1024)
return round(fsize, 2)
if __name__ == '__main__':
list = []
path = r"/home/hadoop/dmp/dmp/"
currtime = "2022-12-31 00:00:00"
for file_name in os.listdir(path):
fullPath = os.path.join(path, file_name)
createTime = get_FileCreateTime(fullPath)
delFlag = createTime < currtime #判断创建日期小于某个日期,即标记为删除
f = Folder(fullPath, createTime, delFlag)
if delFlag:
list.append(f)
for o in list:
print(o.name, o.createTime, o.delFlag)
#shutil.rmtree(o.name) 打开这行即可删除文件夹
标签:name,filePath,Python,delFlag,清理,文件夹,path,os,createTime
From: https://www.cnblogs.com/30go/p/17038490.html