Reputation: 25
ROOT_DIR = "/content/LCDS/MalignantCases"
number_of_images = {}
for dir in os.listdir(ROOT_DIR):
number_of_images[dir] = len(os.listdir(os.path.join(ROOT_DIR, dir)))
when I run the code I get this error
NotADirectoryError Traceback (most recent call last)
<ipython-input-105-4edc0f0385bd> in <module>()
number_of_images[dir] = len(os.listdir(os.path.join(ROOT_DIR, dir)))
NotADirectoryError: [Errno 20] Not a directory: '/content/LCDS/MalignantCases/Malignant case (347).jpg'
What I am doing wrong here ?
Upvotes: 2
Views: 10668
Reputation: 27567
You'll need to check if the object is a file or a directory before attemting to call the os.listdir()
method on it. You can do this using the os.path.isdir()
method:
ROOT_DIR = "/content/LCDS/MalignantCases"
number_of_images = {}
for dir in os.listdir(ROOT_DIR):
joined = os.path.join(ROOT_DIR, dir)
if os.path.isdir(joined):
number_of_images[dir] = len(os.listdir(joined))
A few things to note:
It is considered bad practice to define variables using names that are taken by built-in function, and in your case, dir
is already the name of the built-in function dir()
.
It is recommended by PEP-8 to used 4 spaces as indentation for optimal readability.
Upvotes: 2