How to get relative path of files from defined root directory?

python

Solution

That would be `os.path.relpath()`:

>>> import os
>>> filename = "C:/test/media/blog_images/2013/06/15/yay.gif"
>>> blog_images = "C:/test/media/blog_images/"
>>> os.path.relpath(filename, blog_images)
'2013\\06\\15\\yay.gif'

Problem

I have the following, ``` base_dir = 'blog_images' dir_to_serve = os.path.abspath(settings.MEDIA_ROOT + base_dir) images = [] allowed_types = ('.jpg', '.jpeg', '.png', '.gif') for root, dirs, files in os.walk(dir_to_serve,topdown=False): for image_file in files: if image_file.endswith((allowed_types)): images.append(image_file) ``` The directory structure i have is the following; ``` media --> blog_images --> <year> --> <month> --> <date> --> files ``` Using os.walk() i am able to get the root of each directory etc, but what i am trying to accomplish is to build a dictionary key off the year/month/date and then list the images under that key. SO for example 2013 year then have month then day and then images for each day so that i can access them by date in the template. How do u get the relative path of the file in that loop in relation to blog_images? How do i build a dictionary for use in a template? What are some of the functions i should be looking at?

Original source