How to get relative file path from a specific root directory?

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 can get the root from each directory, etc., but what I'm trying to accomplish is to create a dictionary key from year / month / date, and then list the images under that key. For example, for example, 2013, then a month and a day, and then images for each day, so that I can access them by the date in the template.

How do you get the relative file path in this loop relative to blog_images? How to create a dictionary for use in a template? What features should I watch?

+4
source share
1 answer

This will 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' 
+4
source

Source: https://habr.com/ru/post/1489501/


All Articles