I'm trying to write some code that deletes all text files from a folder that are older than 30 days.
I am new to python, and I am aware that the code below is not the cleanest. My initial code was more tidy, for example by putting
datetime.datetime.now() and time.ctime(os.path.getctime(foundfile) into variables, but I thought this caused the error: TypeError: can't compare datetime.datetime to str
. But it seems that even with the direct method below I still get this error.
import os
import time
import datetime
for file in os.listdir('/MyDir/'):
foundfile = os.path.join('/MyDir/', file)
if file.endswith('txt') and time.ctime(os.path.getctime(found
file)) < datetime.datetime.now() - datetime.timedelta(days=30):
os.remove(os.path.join('/MyDir/', file))
I would expect the code to subtract 30 days from the current date and then remove all text files that are older, but I get an error: TypeError: can't compare datetime.datetime to str
. I can't get my head around why.