Python file counting script
#1
Sad 
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!
Reply
#2
i don't know of any ready to use python module.
but you should check out os-module. it has a listdir()-method to display folder contents.
to get the filesize use stat() from os.

this combined with some recursion should get you started.

bernd
Reply
#3
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]
Reply
#4
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
Reply
#5
> 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?
Reply

Logout Mark Read Team Forum Stats Members Help
Python file counting script0