没有那个文件或目录(无法找到目录)

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

我正在编写代码来计算每个文件夹中有多少张图片。我有一个数据集文件夹,它包含 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())}')