Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialcsr13
33,293 PointsAny advice?
I am trying to iterate through the [] of files in the directory using os.listdir("backups") with the intention of trying to match the string to the date with the if conditional statement, then trying to remove any file that matches.
It's popping an error so I know I'm missing something.
import os
def delete_by_date(date):
for file in os.listdir("backups"):
if file[:9] == date:
os.remove(file)
1 Answer
Steven Parker
231,275 PointsYou're pretty close, but I can see two issues:
- check the argument sample again, 9 may not be enough characters for the slice
- these files are in the "backups" directory, not the current one, so the name will need to reflect that
csr13
33,293 Pointscsr13
33,293 PointsSteven Parker Ok, I went ahead and tried to followed the advice on the two issues that you brought up.
Tried the following in the for loop, but, both showed errors:
os.listdir(os.getcwd()) and os.listdir(os.path.dirname(os.path.abspath('backups')))
Tried the following slices, also showed errors:
[:10] it popped up an error2 and [:8] it popped up same error as [:9]
Any other clue you are willing to give up?
Steven Parker
231,275 PointsSteven Parker
231,275 PointsOne of your slice choices was correct.
But it's not the "listdir" that needs modification, it was already doing the job of listing the directory. Yet when you perform the "remove", you'll need to modify the name to reflect the file and the directory it is in.
csr13
33,293 Pointscsr13
33,293 PointsAlright, got them both.
"<directory>" and <filename> worked.
Thank you!