python noob: count files in a directory

Status
Not open for further replies.

Uncle Meat

Ars Scholae Palatinae
659
I need to count the number of files in a directory, excluding subdirs and hidden files.

This works:
Code:
numfiles = len([f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f))])

but includes .hidden files.

This excludes hidden files (filename beginning with '.' in this case):
Code:
numfiles = len([f for f in os.listdir(dir_name) if f[0] != '.'])

but then I'm stuck counting subdirs again. There must be some way to combine those two 'if' statements but I haven't the slightest idea how.
 

Alamout

Ars Legatus Legionis
27,285
You use 'and', just like in any other if statement.
Code:
numfiles = len([f for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f)) and f[0] != '.'])
And for extra credit: using a generator will save memory if your directory is ludicrously enormous:
Code:
numfiles = sum(1 for f in os.listdir(dir_name) if os.path.isfile(os.path.join(dir_name, f)) and f[0] != '.')
 
Status
Not open for further replies.