Search code examples
pythonlistdir

No such file or directory (Unable to find the directory)


I am writing code for calculating how many images are there in each folder. I have a folder that is dataset and it contains 12 sub-folders. Therefore, I want to show each amount of image data in every folder.

My code:

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

But I get the error below:

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

Solution

  • You have forgotten to add a trailing slash '/' to your string concatenation. Also, you need to remove the first dot from the path, as I understood from your comment.

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

    But I would generally advice you to use os.path.join to avoid such errors in the first place, instead of manually adding path strings.

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