Posts: 4
Joined: Jul 2005
Reputation:
0
2005-07-11, 21:52
does anyone know a (python) script for counting the number of files within a directory and all its subfolders? for example, how could i find the number of .mp3 files that exist on c:\ ?
basically, i want to calculate an average size for all the .mp3 files on a specified drive. surely someone knows how to do that...
thanks!
Posts: 4
Joined: Jul 2005
Reputation:
0
thanks. i found some help from another forum. here is a script which returns the average file size (.mp3 and .wav) of specified directory:
######################################################
# avgfilesize.py
# this python script prints out the average file size
# for a specified directory in kb.
# this script searches all folders and subfolders in
# the specified directory "direc."
# to change the directory this script searches,
# modify the "direc" variable below. for example,
# direc = "c:\music\the beatles"
######################################################
import os
from os.path import join, getsize
# ****************************************************
# change the directory here...
direc = "h:\my music"
# ****************************************************
######################################################
# function which returns the average file size of
# files with extensions "ending1" or "ending2"
# in the directory "startdir"
######################################################
def summarize(startdir, ending1, ending2):
size_sum = 0
number_of_files = 0
# search all of the folders and subfolders in "startdir"
for root, dirs, files in os.walk(startdir):
for name in files:
if name.endswith(ending1) or name.endswith(ending2):
number_of_files += 1
size_sum += getsize(join(root, name))
# calculate average in bytes
return size_sum / number_of_files
#######################################################
# call function to calculate average
average = summarize(direc, ".mp3", ".wma")
# figure average in kb...
avginkb = average/1024
# print message to user
print "average file size for ", direc, " is ", avginkb, " kb"
[code]
Posts: 211
Joined: Mar 2005
Reputation:
0
Bernd
Senior Member
Posts: 211
great,
must have overlooked os.walk(). it does exactly what you wanted.
but as a real python-developer you would of course pass a regular expression to specify which files to count instead of ending1 and ending2. :d
bernd
Posts: 4
Joined: Jul 2005
Reputation:
0
> pass a regular expression to specify which files to count instead > of ending1 and ending2
what do you mean by this? what do you mean by "regular expression?" do you mean prompt the user for input?