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

Michael Jorgensen
Michael Jorgensen
1,189 Points

I've tested this problem on my laptop and it works just fine.

Maybe I'm missing something, but from the instructions and examples this "cleans up" the file type consistency

consistency.py
import os

# 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

import re

def cleanup(path):
    # your code here
    for root, dirs, files in os.walk(path):
        for file in files:
            result = re.search("([a-z0-9]+)(-)([0-9]{4}-[0-9]{2}-[0-9]{2})(.[a-z]+)", file)
            if(result):
                replace = result.group(3) + result.group(2) + result.group(1) + result.group(4)
                if(os.path.isfile(path + '\\' + file)):
                    os.remove(root + '\\' + file)
                    filenew = open(root + '\\' + replace, 'w')
                    filenew.close

1 Answer

Kevin Ryan
Kevin Ryan
6,572 Points

It looks like. You are removing the existing file and creating a new one with the same name. Use os.rename instead.

for dname,subdirs,files in os.walk(path):
    for fname in files:
        #modify file name and store in result
        os.rename(os.path.join(path, fname),os.path.join(path, result))