# Imports import sys # For argv import os # For system import glob # For globbing # Variables do not have to be initialized and do not have type myVar = 0 myString = 'one' myList = [1, 2, 3] myDict = { 1: "first", 2: "second" } # dictionary is a hashtable print "Vars: ", myVar, myString, myList[0], myDict[1] # Command line arguments are an array of string print "Number of args: ", len(sys.argv), # Trailing comma suppresses new line print " Program name: ", sys.argv[0] # for loop for i in (1,2,3,4,5,6): # Also: for i in range(1,6) if ( i == 5 ): os.system('uname -a') elif ( i == 6 ): print "Concat" + "enated" else: pass # Comment, do nothing # file processing file = open("crib-test.txt", "w") file.write("comma,separated,file\n") file.writelines(["and,several,lines\n", "at,that,eh\n"]) file.close() file = open("crib-test.txt", "r") allLines = file.readlines() file.close() print "File contains: ", allLines for lineNum in range( len(allLines) ): splitLine = allLines[lineNum].split(',') # Split string on ',' into array splitLine[1] = splitLine[1].capitalize() allLines[lineNum] = ','.join(splitLine) # Turn ["one", "two"] into "one,two" print "Lines after: ", allLines # Files in directory allFiles = glob.glob("*") fileIndex = 0 while fileIndex < len(allFiles): filename = allFiles[fileIndex] print filename +": ", sys.stdout.flush() # Otherwise 'system' output gets there first retVal = os.system("sum %s" % filename) # Grab return value so that it does not appear on screen fileIndex += 1 # Functional programming # map() performs the passed function on each tem in the list and returns a list of results # for e in lst: func(e) is the same as map(func, lst) # reduce() performs the passed function on each subsequent item and an internal accumulator of the final result. # reduce( func, list ) # filter() uses the passed function to evaluate each item in a list and returns a list of the elements that passed # filter( func, list )