简体   繁体   中英

Recursively read through a folder tree and determine which folders have files

I've written a program to look through images inside a folder and extract the embedded EXIF data. Currently I'm using the code below to get paths for all the files inside a folder, the variable 'folder_name' is input by the user. The list created is then used by the program to cycle through all the images.

file_names = glob(join(expanduser('~'),'Desktop',folder_name,'*'))

Now I want to add a bit of functionality, that is the ability to look through a folder tree and return only the folders with images/files in them. This list could then be passed into the bit of code above to do the rest. I just need a pointer as to where to look to develop this.

Also how could I select and output just the image files, using endswith(.jpg) on the file path didn't work due to case sensitivity.

You can try os.walk + mimetypes.guess_type like so

import os
import os.path
import mimetypes
top="."
imagefiles=[]
for root, dirs, files in os.walk(top):
    for fn in files:
        t,e= mimetypes.guess_type(fn, strict=False)
        if t.startswith("image/"):
            imagefiles.append(os.path.join(root,fn)

您可以通过在比较两个字符串之前对两个字符串应用.lower()字符串方法来解决区分大小写的问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM