# L-25 MCS 275 Wed 10 Mar 2010 : grabpyhead.py # Grabs the header line of all .py programs. # When the file starts with '#!', the header # line is not the first but the second line. # Every file has four fields: # type, number, date, and file name. import os def HasPyExt(name): """ Returns True if the name ends in ".py", returns False otherwise. """ try: if name[-3:] == '.py': return True else: return False except: return False def StartPath(line): """ Returns True if the line appears to be the path of the python interpreter, returns False otherwise. """ try: if line[0:2] == '#!': return True else: return False except: return False def SplitFields(line): """ Returns a tuple with the fields of the header. """ L0 = line.split(' : ') fname = L0[1] L1 = L0[0].split(' MCS 275 ') fdate = L1[1] L2 = L1[0].split(' ') L3 = L2[1].split('-') ftype = L3[0] fnumb = L3[1] return (ftype,fnumb,fdate,fname) def EnumFields(d,f): """ Enumerates all fields in the header of the .py files in the directory d. For each field, the function f is called. Returns the number of .py files. """ L = os.listdir(d) cnt = 0 for filename in L: if HasPyExt(filename): cnt = cnt + 1 file = open(filename,'r') s = file.readline() if StartPath(s): s = file.readline() try: f(SplitFields(s[:-1])) # omit \n except: print 'exception occured with file ' + filename file.close() return cnt def PrintFields(s): """ Use as argument to test the enumerator. """ print s def main(): """ Prints the header of all .py files in the current directory. """ n = EnumFields('.',PrintFields) print 'counted %d .py files' % n if __name__ == "__main__": main()