Python – Count files in Folder by Python Programming

countdirectoryfilenumberspython

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

Best Solution

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