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 Consistency

David Sampimon
David Sampimon
12,026 Points

Why won't this pass the challenge?

So I solved this challenge locally on two different ways, but both do not pass the online challenge. Since I am not sure why both solutions do not pass, I got stuck.

Solution 1:

import os
import re

# Filenames consist of a username (alphanumeric, 3-12 characters)
# and a date (four digit year, two digit month, two digit day),
# and an extension. They should end up in the format
# year-month-day-username.extension.

# Example: kennethlove2-2012-04-29.txt becomes 2012-04-29-kennethlove2.txt
date_regex = r'\d{4}-\d{2}-\d{2}'

def cleanup(path):
    filename, file_extension = os.path.splitext(path)
    date = re.search(date_regex, filename).group(0)
    username = filename.split('-')[0]
    new_name = f'{date}-{username}{file_extension}'
    os.rename(path, new_name)

solution 2

def cleanup(path):
    filename, file_extension = os.path.splitext(path)
    filename_lst = filename.split('-')
    return f'{filename_lst[1]}-{filename_lst[2]}-{filename_lst[3]}-{filename_lst[0]}{file_extension}'
consistency.py
import os
import re

# Filenames consist of a username (alphanumeric, 3-12 characters)
# and a date (four digit year, two digit month, two digit day),
# and an extension. They should end up in the format
# year-month-day-username.extension.

# Example: kennethlove2-2012-04-29.txt becomes 2012-04-29-kennethlove2.txt
date_regex = r'\d{4}-\d{2}-\d{2}'

def cleanup(path):
    filename, file_extension = os.path.splitext(path)
    date = re.search(date_regex, filename).group(0)
    username = filename.split('-')[0]
    new_name = f'{date}-{username}{file_extension}'
    os.rename(path, new_name)

1 Answer

In the challenge description, it says This function should take a string which will be a path to a local directory. but your code looks like it takes in a path to a file instead of a path to a folder.

David Sampimon
David Sampimon
12,026 Points

You were right, thank you. Completely overlooked that