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.
A:
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;-).
Alex Martelli
2010-03-02 01:04:41
A:
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
ghostdog74
2010-03-02 01:34:09
Extensions aren't always 3 chars, might be better to do files.split('.')[-1].lower() so you can include variations like jpeg
Davy8
2010-03-15 01:09:33
A:
I've been looking for a similar solution! Nice GhostDog! Any idea how you would only return files that don't contain a certain phrase; e.g. return only files that don't include the phrase "Preview" or multiple phrases?
Ian
2010-03-15 00:49:09