如何从定义的根目录获取文件的相对路径?

Dee*_*eep 5 python

我有以下内容,

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)
Run Code Online (Sandbox Code Playgroud)

我的目录结构如下;

media --> blog_images --> <year> --> <month> --> <date> --> files
Run Code Online (Sandbox Code Playgroud)

使用 os.walk() 我能够获取每个目录的根目录等,但我想要完成的是构建一个年/月/日期的字典键,然后列出该键下的图像。例如,2013 年有月份、日期,然后是每天的图像,以便我可以在模板中按日期访问它们。

如何获取该循环中文件相对于 blog_images 的相对路径?如何构建在模板中使用的字典?我应该关注哪些功能?

Tim*_*ker 5

那将是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'
Run Code Online (Sandbox Code Playgroud)