首页 > 解决方案 > 没有这样的文件或目录(找不到目录)

问题描述

我正在编写用于计算每个文件夹中有多少图像的代码。我有一个数据集文件夹,它包含 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'

标签: pythonlistdir

解决方案


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

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))
    #....

推荐阅读