简体   繁体   中英

How can I load .jpg images in directory under directory?

I need to load images such as 001.jpg, 045.jpg, etc.. in directory "0000045", but there are other image directory in folder "image". My code was this;

import glob

path = r'C:\Users\user\PycharmProjects\dg\image'
file_list = glob.glob(path)
file_list_jpg = [file for file in file_list if file.endswith(".jpg")]

print ("file_list_py: {}".format(file_list_jpg))

but the result was

file_list_py: []

I want to see 001.jpg or else but there was nothing :( Can anybody help me on this problem?

Your Directory root Structure is ,

Image--
      |
      0000045--
              |
              (Image files with ".jpg" or anyother format )

But according to your code ,

path = r'C:\Users\user\PycharmProjects\dg\image'
file_list = glob.glob(path)

You are accessing image directory which contains all other directory ( like 0000045 dir ). So the file_list will be of the directory names.

file_list_jpg = [file for file in file_list if file.endswith(".jpg")]

Hence there are no names in file_list which ends with .jpg .So the list is empty .

Inorder to access the image files ,

import glob
path = r'C:\Users\user\PycharmProjects\dg\image'

dir_list = glob.glob(path)
file_list = []
for directory in dir_list:
    path = r'C:\Users\user\PycharmProjects\dg\image' +"\"+directory
    file_list += glob.glob(path)

file_list_jpg = [file for file in file_list if file.endswith(".jpg")]

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