[Tutor] regular expressions

Sandip Bhattacharya sandip at linux-delhi.org
Thu Mar 11 03:09:53 EST 2004


Christopher Spears wrote:
> I am hacking away on my final project:
> 
> A file with a name like picture.jpg is said to have an
> extension of "jpg"; i.e. the extension of a file is
> the part of the file after the final period in its
> name. Write a program that takes as an argument the
> name of a directory (folder) and then finds the
> extension of each file. Then, for each extension
> found, it prints the number of files with that
> extension and the minimum, average, and maximum size
> for files with that extension in the selected
> directory.
> 
> Here is my code so far:
> 

Thanks for giving me a pet problem to get me up to speed with python. :)

Are you sure you want to use regular expressions for this? The os.path 
module gives you all you need.

Here is my code for doing it without regexp. No intention to spoil your 
work. Just took it as my excercise. ;)

====================
#!/usr/bin/python

import os.path,os
from stat import ST_SIZE

dirpath = raw_input("Enter path:")

filelist = os.listdir(dirpath)
extlist={}

for fname in filelist:
     if not os.path.isfile(fname):
         pass
     undef,file = os.path.split(fname)
     b,e= os.path.splitext(file)
     size = os.stat(dirpath+"/"+fname)[ST_SIZE]
     if not extlist.has_key(e):

         extlist[e] = (1,size,size,size)
     else:
         n,smin,savg,smax=extlist[e]
         if smin > size: smin = size
         if smax < size: smax = size
         savg = (savg*n +  size)/(n+1)
         n+=1
         extlist[e] = (n,smin,savg,smax)


for ext in extlist.keys():
     n,smin,savg,smax=extlist[ext]
     print "%20s %3d %8d %8d %8d" % (ext[1:], n,smin,savg,smax)
=============


-- 
Sandip Bhattacharya
sandip (at) puroga.com
Puroga Technologies Pvt. Ltd.
Work: http://www.puroga.com        Home: http://www.sandipb.net

GPG: 51A4 6C57 4BC6 8C82 6A65 AE78 B1A1 2280 A129 0FF3




More information about the Tutor mailing list