我有以下内容,
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)
我的目录结构如下;
media --> blog_images --> <year> --> <month> --> <date> --> files
使用 os.walk() 我能够获取每个目录的根等,但我想要完成的是建立一个年/月/日的字典键,然后在该键下列出图像。因此,例如 2013 年,然后有月份,然后是日期,然后是每一天的图像,以便我可以在模板中按日期访问它们。
如何获取该循环中文件相对于 blog_images 的相对路径? 如何构建用于模板的字典? 我应该关注哪些功能?
最佳答案
那就是 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'
关于python - 如何从定义的根目录获取文件的相对路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17449385/