Python 没有这样的文件或目录(找不到目录)
我正在编写代码来计算每个文件夹中有多少图像。我有一个文件夹是dataset,它包含12个子文件夹。因此,我想显示每个文件夹中的每个图像数据量 我的代码:Python 没有这样的文件或目录(找不到目录),python,listdir,Python,Listdir,我正在编写代码来计算每个文件夹中有多少图像。我有一个文件夹是dataset,它包含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 f
# 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)
但我通常会建议您首先使用以避免此类错误,而不是手动添加路径字符串
for folder in folder_list:
# set the path to a folder
path = os.path.join('/content/dataset' + str(folder))
#....
我将使用
pathlib
和dict
来存储结果
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())}')
你是linux还是windows?在windows中使用“\\”。
path='/content/dataset/'+str(文件夹)
您忘记了数据集后面的/
。错误显示为allWindows,我正在使用google colab平台,但问题现在出现在以下行中:image_list=os.listdir(path)@Alex metsai错误是什么?此外,也许你应该做path='/content/dataset'+str(folder)
而不是path='./content/dataset'+str(folder)
?没有第一个点。先生,我已经更新了我的答案,并且解决了它。但现在我面临的问题与我发布的更新问题相同。链接在这里@Alex Metsai更新了我的答案。我会尽快看另一个问题我遇到了一个错误:未定义名称“pth”
。。之后,我将pth重写为路径
然后出现另一个错误'str'对象没有属性
rglob`@Eric Truett