Python目录列表返回到Django模板

发布于 2024-08-23 18:51:44 字数 120 浏览 3 评论 0原文

这里是 Python 新手。我有一个图像目录,我需要将这些文件的名称和 url 返回到 django 模板,我可以循环访问链接。我知道这将是服务器路径,但我可以通过 JS 修改它。我尝试过 os.walk,但我一直得到空结果。

Total Python newb here. I have a images directory and I need to return the names and urls of those files to a django template that I can loop through for links. I know it will be the server path, but I can modify it via JS. I've tried os.walk, but I keep getting empty results.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

无悔心 2024-08-30 18:51:44

如果您的图像位于一个目录中

import os
root="/my"
Path=os.path.join(root,"path","images")
os.chdir(Path)
for files in os.listdir("."):
    if files[-3:].lower() in ["gif","png","jpg","bmp"] :
         print "image file: ",files

If your images are in one directory

import os
root="/my"
Path=os.path.join(root,"path","images")
os.chdir(Path)
for files in os.listdir("."):
    if files[-3:].lower() in ["gif","png","jpg","bmp"] :
         print "image file: ",files
谁人与我共长歌 2024-08-30 18:51:44

如果它是单个目录,os.listdir('thedirectory') 将为您提供一个似乎适合您的目的的文件名字符串列表(尽管它不会生成“url”——不确定你想如何制作它们?)。如果您需要一整目录(递归地包括子目录),那么值得调试您使用os.walk失败的尝试,但我们很难发现其中的错误我们没有显示的代码;-)。

If it's a single directory, os.listdir('thedirectory') will give you a list of filename strings that seem to be suitable for your purposes (though it won't make "the urls" -- not sure how you want to make them?). If you need a whole tree of directories (recursively including subdirectories) then it's worth debugging your failed attempts at using os.walk, but it's hard for us to spot the bugs in code that we're not shown;-).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文