我无法想出一种安全删除提供的根目录中除最近创建或更新的文件夹之外的所有文件夹的方法。我有这个基本的结构设置,但我不知道如何从这里开始:
for root, folders, files in os.walk(output_folder):
for folder in folders:
答案 0 :(得分:2)
你可以找到像这样的最新文件夹
import os, shutil
newest_folder = max(folders, key=os.path.getmtime)
for fname in folders:
if fname != newest_folder:
shutil.rmtree(folder)
根据您的具体要求,您可能希望使用getctime
代替getmtime
答案 1 :(得分:1)
这可能适合您: -
import os
import datetime as dt
import shutil
now = dt.datetime.now()
ago = now-dt.timedelta(minutes=30) #Mention the required time
for root, dirs,files in os.walk('/home/piyush/pppptest'): #put required directory path
for fname in files:
path = os.path.join(root, fname)
st = os.stat(path)
mtime = dt.datetime.fromtimestamp(st.st_mtime) #Gives you the modified time of file
# print mtime
if mtime > ago:
print('%s modified %s'%(path, mtime)) #You can check path and modified and work on it as per your requirement
shutil.rmtree('path') #You can delete it.