如何检查文件夹中的文件以及检查子文件夹中的文件后

时间:2018-10-26 02:47:22

标签: python-3.x file jpeg

我有这样的结构:

Root_folder:
    |
    |__sub_folder1
    |
    |__sub_folder2
    |
    |__sub_folder3
    |
    |__Photo_file.jpeg

在检查子文件夹中的photo_files之前,但是如果我的根目录中有jpeg_file,我会得到一个错误。

def get_photos(path):
    photos = []
    photos_path = []
    for folders in os.listdir(path):
        for jpeg in os.listdir(path + folders):
            photos_path.append(path + folders + '/' + jpeg)
            photos.append(jpeg)
    return photos,  photos_path   

如何将root的jpeg和sub_folders的jpeg附加到列表中?

def get_photos(path):
    photos = []
    photos_path = []

    for folders in os.listdir(path):
        if re.match('.*\.jpeg|.*\.jpg|.*\.png', folders):
            photos_path.append(path + folders)
            photos.append(folders)
    for folders in os.listdir(path):
        for jpeg in os.listdir(path + folders):
            photos_path.append(path + folders + '/' + jpeg)
            photos.append(jpeg)

    return photos,  photos_path 

据我所知,检查root是否具有jpeg,然后附加它们。但是子文件夹的逻辑应该是什么? 现在,它也尝试使用jpeg_file名称作为子文件夹,因此出现错误

1 个答案:

答案 0 :(得分:0)

这对我有用:

def get_photos(path):

    photos = []
    photos_path = []

    for folders in os.listdir(path):
        if re.match('.*\.jpeg|.*\.jpg|.*\.png', folders):
            photos_path.append(path + folders)
            photos.append(folders)
        else:
            for jpeg in os.listdir(path + folders):
                photos_path.append(path + folders + '/' + jpeg)
                photos.append(jpeg)

    return photos,  photos_path