Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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 12,641 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