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

Make a function named delete_by_date. PYTHON FOR FILE SYSTEMS

totall lost. please help

purging.py
import os

def delete_by_date(path):
    path = path+'/backups'
    os.remove(path)

1 Answer

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

Look at the instructions again. There's more to the path than the date string. The date is inside the filename itself.

import os

def delete_by_date(date_string):
    for root, dirs, files in os.walk('backups'):
        for single_file in files:
            if date_string in single_file:
                os.remove(os.path.join(root, single_file))

Using the tools we've been give "so far," I've opted to walk the directory as we did in the earlier module.

Using os.scandir for the second half of the challenge looks like this:

def delete_by_user(user_string):
    files = []
    for each_file in os.scandir('backups'):
        if each_file.is_file():
            files.append(each_file.path)
    for single_file in files:
        if user_string in single_file:
            os.remove(single_file)
justlevy
justlevy
6,325 Points

Stephen Cole - great code but this didn't work for me in the Treehouse Challenge. I can confirm it worked on my local Windows machine running Visual Studio Code.

Sidenote - I learned that os.scandir isn't iterable, correct? That's why we created an empty list, files, and append each file to that list?