Fahadkalis
Fahadkalis

Reputation: 3261

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

Upvotes: 4

Views: 49854

Answers (4)

julio
julio

Reputation: 121

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))

Upvotes: 12

Padraic Cunningham
Padraic Cunningham

Reputation: 180391

It needs to be a lowercase h for ubuntu homeand you also need to supply your username, so either use path = "/home/user_name/python" or os.path.expanduser.

os.path.expanduser will return something like /home/username/python:

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

Upvotes: 3

Digisec
Digisec

Reputation: 700

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

Upvotes: 12

Jacobr365
Jacobr365

Reputation: 846

import glob, os
file_count = 0
WorkingPath = os.path.dirname(os.path.abspath(__file__))
for file in glob.glob(os.path.join(WorkingPath, '*.*')):
    file_count += 1

Just stick the source for that into whatever directory you are counting files in. This only counts files not folders.

Upvotes: 1

Related Questions