没有那个文件或目录找不到目录

问题描述

我正在编写用于计算每个文件夹中有多少图像的代码我有一个数据集文件夹,它包含 12 个子文件夹。因此,我想显示每个文件夹中的每个图像数据量。

我的代码

# get a list of image folders
folder_list = os.listdir('/content/dataset')

total_images = 0

# loop through each folder
for folder in folder_list:
    # set the path to a folder
    path = './content/dataset' + str(folder)
    # get a list of images in that folder
    images_list = os.listdir(path)
    # get the length of the list
    num_images = len(images_list)
    
    total_images = total_images + num_images
    # print the result
    print(str(folder) + ':' + ' ' + str(num_images))
    
print('\n')
# print the total number of images available
print('Total Images: ',total_images)

但我收到以下错误

error: FileNotFoundError: [Errno 2] No such file or directory: '/content/datasetFat Hen'

解决方法

您忘记在字符串连接中添加尾部斜杠“/”。此外,正如我从您的评论中了解到的,您需要从路径中删除第一个点。

path = '/content/dataset/' + str(folder)

但我通常建议您首先使用 os.path.join 来避免此类错误,而不是手动添加路径字符串。

for folder in folder_list:
    # set the path to a folder
    path = os.path.join('/content/dataset' + str(folder))
    #....
,

我会使用带有 pathlibdict 来存储结果

from pathlib import Path

dirs = {}
base = Path('/content/dataset')
for folder in [pth for pth in base.glob('*') if pth.is_dir()]:
    dirs[folder.as_posix()] = len([subpth for subpth in folder.rglob('*') if subpth.is_file()])

for k,v in dirs.items():
    print(f'{k}: {v}')
    
print()
print(f'Total Images: {sum(dirs.values())}')