computing
  • 2

Python – Count File By Extension

  • 2

Hi,

I was trying to write a python script to take in a directory, recursive scan it for all files, keep track the number of files with a particular extension and print how many files of each extension type there were.

Unfortunately I’m getting the following error:

Traceback (most recent call last):
  File "H:\search.py", line 30, in <module>
    extensionarray = check_format(filearray)
  File "H:\search.py", line 18, in check_format
    val = index(result1, extension)
  File "H:\search.py", line 13, in index
    return next((i for i in xrange(len(seq)) if f(seq[i])), 'None')
  File "H:\search.py", line 13, in <genexpr>
    return next((i for i in xrange(len(seq)) if f(seq[i])), 'None')
TypeError: 'str' object is not callable

I would appreciate any help, this was what I have so far:

 

import os, sys

def get_all_files(srchpath):
	allfiles = []
	for root, dirs, files in os.walk(srchpath):
		for file in files:
			pathname = os.path.join(root, file)
			extension = os.path.splitext(file)[1]
			allfiles.append([file, pathname, extension])
	return allfiles
	
def index(seq, f):
    return next((i for i in xrange(len(seq)) if f(seq[i])), 'None')
	
def check_format(thefiles):
	result1 = []
	for filename, pathname, extension in thefiles:
		val = index(result1, extension)
		if val == 'None':
			result1.append([extension, 0])
		else:
			result1[val][1] += 1
	return result1

def print_array(thearray):
	for val in range(1, len(thearray)):
		print thearray[val]

filearray = get_all_files(sys.argv[1])
extensionarray = check_format(filearray)
print_array(extensionarray)

** thanks nbrane for catching my first mistake!

Share

1 Answer

  1. you, me both brother – you’re an order of magnitude beyond me since i know zero – but i am interested to learn. You have made a start!
    what is f, and where is it defined or established or assigned?
    f(seq[i])), ‘None’)
    if f is undefined, interp. might be looking for a function “f”. but my take on it is that f is supposed to be either an array of, or a string of extensions. i don’t know how arrays expressed in python: whether [] or (). might be you are not expressing the array definition as py wants it?
    my guess is the critical-issue is item “f”.

    • 0