1

I have a folder having 7000+ images. I want to find the exact length of these images.

path = "/content/drive/MyDrive/iuxray/images/images_normalized"

I use the following code for printing the length of total number of images in this folder.

print(f"Number of images: {len(path)}")

But it prints just 54 images like below

Number of images: 54

So I want to know where am I doing wrong. How to print the exact number of images

odaiwa
  • 315
  • 2
  • 14
  • 4
    54 is the number of characters in the path string you defined. You probably want to look at the `os` package and the `listdir` function (that'll give you a list of file names in a directory). – TravisJ Oct 15 '22 at 14:58
  • 2
    Does this answer your question? [How to count the number of files in a directory using Python](https://stackoverflow.com/questions/2632205/how-to-count-the-number-of-files-in-a-directory-using-python) – odaiwa Oct 15 '22 at 15:05

1 Answers1

1

You were printing the length of the directory path which is a string, this should give the list of files and its length

import os
path = "/content/drive/MyDrive/iuxray/images/images_normalized"
fileList=os.listdir(path)
print(len(fileList))
# for checking whether file is not a directory
print(len([fname for fname in os.listdir(path) if os.path.isfile(os.path.join(path, fname))]))
Kaneki21
  • 1,323
  • 2
  • 4
  • 22
  • 2
    This will include files & directories. This answer explains how to specifically get a list of files using `pathlib` and `is_file()` https://stackoverflow.com/a/40216619/13188999. – Ed Kloczko Oct 15 '22 at 16:08
  • Includes sub-directories in the count. You could filter it out with a list comprehension and then take it's length. Also consider, while not in the question verification of the files to be images themselves. – Naitik Mundra Oct 16 '22 at 19:13