python - 没有这样的文件或目录(找不到目录)
问题描述
我正在编写用于计算每个文件夹中有多少图像的代码。我有一个数据集文件夹,它包含 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))
#....
推荐阅读
- postgresql - 如何使用标签标记变更集或变更日志文件 - webdevops/liquibase
- grails - 找不到构造函数“java.lang.String”的参数 0
- java - 如何确保 Java 线程永远不会运行无限循环?
- java - 如何在java中按右移?
- python - 为什么使用 while 循环可以使程序工作,但我原来的 for 循环不起作用?(DNA pset6)
- javascript - 查找最后一次说出一个词
- android - 无法解决 response.body().string() 的问题
- jupyter-notebook - Jupyter 中单元格之间的乳胶方程数重置为 1
- node.js - “npm install”安装不熟悉的文件
- c - 如何使用 Bash shell 脚本存储 C 程序的输出