python根據文件創建時間刪除文件
最近遇到一個需求,刪除今天創建時間之外的文件,簡單寫了一下,希望對大家有用
def check_path():
""檢查目標文件夾是否存在,不存在就創建"""
full_path = os.path.join(settings.MEDIA_ROOT, "file")
if not os.path.exists(full_path):
os.makedirs(full_path)
return full_path
def delete_old_file():
full_path = scheck_path()
today = datetime.datetime.today().strftime('%Y-%m-%d')
for file in os.listdir(full_path):
file_path = os.path.join(full_path, file)
t = os.path.getmtime(file_path)
timeStruce = time.localtime(t)
times = time.strftime('%Y-%m-%d %H:%M:%S', timeStruce)
if today not in times:
if os.path.exists(file_path):
os.remove(file_path)
有些依賴需要自己導入,在這裡我就不導入了