I am trying to delete old folders and I am asking does anyone know how to set 开发者_开发知识库up a variable that allows me to check the variable 'todaystr' which is today's date and minus 7 days of this string and store it another variable. I am wanting to automatically delete old files after a week. Below shows the variable 'todaystr' being set up.
todaystr = datetime.date.today().isoformat()
I would like to create a variable 'oldfile' that stores the current date minus 7 days so I can delete the file with this date. Thanks for any help.
import datetime
import os
import shutil
threshold = datetime.datetime.now() + datetime.timedelta(days=-7)
file_time = datetime.datetime.fromtimestamp(os.path.getmtime('/folder_name'))
if file_time < threshold:
shutil.rmtree('/folder_name')
I relation to the above answer it works very well, the code I used was different in the end. I create the name of the folder with the current date, so when the nightly build runs it will only delete the folder named from 7 days ago. The code is as follows:
import datetime
import os
import calendar
today = datetime.date.today()
todaystr = datetime.date.today().isoformat()
minus_seven = today.replace(day=today.day-7).isoformat()
if os.path.exists(minus_seven):
os.system("sudo rm -rf "+minus_seven)
print 'Sandboxes from 7 days ago removed'
I used linux the delete the folder as I have some linux incorporated into my code and it runs good like this.
精彩评论