Introduction
to Python Programming
Assignment
1
Sample output when called from DOS shell.

Disclaimer: Normally, I would have used regular expressions (re module) with this type of application. The instructor agreed, however he noted that regular expressions is not part of standard Python and he wanted to first emphasize standard Python string methods. He later introduced the module, Elementtree, which is one of numerous packages dedicated to XML processing.
#!/usr/bin/env python
"""
Assignment 1:
Parse xml file. Look for product name and unit price,
build a dictionary and then print all records.
This program assumes product name and unit price tags are not multiline
and that product name precedes the unit price.
DOS Shell Usage:
assignment1.py <inputfile>
"""
import sys
import string
# extract the tag item at foundIndex
def getItem(line,foundIndex):
substring = line[foundIndex:]
foundIndex = string.find(substring,">")
substring = substring[foundIndex+1:]
foundIndex = string.find(substring,"<")
substring = substring[:foundIndex]
return substring
def main():
# process file input argument
args = sys.argv[1:]
if len(args) > 0:
xmlpath = args[0]
else:
print "*** Error: Missing input file argument ***"
sys.stdout.write(__doc__)
sys.exit(1)
try:
xmlin = open(xmlpath,'r')
except:
print "Error: Unable to open", xmlpath
sys.exit(1)
# read all file input lines into a list
# initialize dictionary and tag items
xmlLines = xmlin.readlines()
productprice = {}
productname = unitprice = ''
# search for tag items line by line and build dictionary
# assume productname occurs before unit price and tag items are not mult-line
for line in xmlLines:
if (productname == ''):
foundIndex = string.find(line,"productname")
if foundIndex > -1:
productname = getItem(line,foundIndex)
else:
foundIndex = string.find(line,"unitprice")
if foundIndex > -1:
unitprice = getItem(line,foundIndex)
productprice[productname] = unitprice
productname = unitprice = ''
# print the record
print "Product Name".ljust(40),"Unit Price".ljust(10)
keys = productprice.keys()
# keys.sort()
for product in keys:
print product.ljust(40),productprice[product].ljust(10)
xmlin.close()
# accomodate Windows
# print "\nHit <Enter> to exit program.\n"
# raw_input()
if __name__ == '__main__':
main()