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 trial

Python Python for File Systems Manipulation Purging

Robert Bird
Robert Bird
26,122 Points

This is for the purging python challenge in Python File System. Not really sure why this answer is not working.

import os import re

def delete_by_date(date_string): dir_list = os.listdir() for i in dir_list: if date_string in i: os.remove(i) else: continue

purging.py
import os
import re

def delete_by_date(date_string):
    dir_list = os.listdir()
    for i in dir_list:
        if date_string in i:
            os.remove(i)
        else:
            continue

1 Answer

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,809 Points

This is what worked for me:

import os

def delete_by_date(date_string):
    for entry in os.scandir('backups'):
        if entry.is_file() and date_string in entry.name:
            os.remove(entry.path)
    return

Speaking from experience, testing whether or not an entry is a file is important.

Also, it wasn't enough to is iff date_string was in entry. It has to be in entry.name.

Robert Bird
Robert Bird
26,122 Points

Thank you very much Stephen, that works nicely. And thanks for the tip about checking that entry is a file, much appreciated