Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count files in Folder by Python Programming

I am trying to count number of files in my folder (/Home/python) for that reason I make a short program

import os.path
path = '/Home/python'
num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])

but it is given me an error like that

Traceback (most recent call last):
  File "count_number_of_files_folder.py", line 3, in <module>
    num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])
OSError: [Errno 2] No such file or directory: '/Home/python'

Guys can you plz help me to make it bug free program. Thank You

enter image description here

like image 319
Fahadkalis Avatar asked Oct 17 '25 20:10

Fahadkalis


2 Answers

Try this instead

import os.path
path = os.getenv('HOME') + '/python'
num_files = len([f for f in os.listdir(path)if os.path.isfile(os.path.join(path, f))])

This is because you are not in /home/python. You are actually in your home directory which is /home/$USER/python. If you do the following, in a terminal, you will see where you are.

cd ~/python && pwd
like image 169
Digisec Avatar answered Oct 20 '25 10:10

Digisec


I think this is the easiest way:

import os

img_folder_path = 'C:/FolderName/FolderName2/IMG/'
dirListing = os.listdir(img_folder_path)

print(len(dirListing))
like image 32
julio Avatar answered Oct 20 '25 09:10

julio



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!