Reading and Working with CSV files

 Suppose that you have a file called sample.csv (right-click to download) which contains information on a group of people: names, ages and salaries.  The file, when it's viewed in a text editor looks like this:

Name,Age,Salary
Harry,16,12.8
Ron,15,9.77
Hermione,16,16.3
Voldy,45,28.1

Suppose your job is to find the average age of the people in the group.  Here's how -- but first, you should read the explanations in File Reading/Writing.  Remember that when Python reads the data into a string variable, it will look like:

'Name,Age,Salary\nHarry,16,12.8\nRon,15,9.77\nHermione,16,16.3\nVoldy,45,28.1\n'

So, here's the code:

def AverageAge(filename):
	# open the file and read its contents into the string variable "alldata"
	try:
		straw=open(filename,'r')
	except:
		# Whoops, probably a typo in the filename, cannot open it.
		return 0
	alldata=straw.read()
        straw.close()

	lines=alldata.split('\n')
	total_age=0
	numdata=0

	# we'll use "lines[1:]" below to ignore the first line in the file
	for aline in lines[1:]:
		# now, we'll separate the line into its pieces
		pieces=aline.split(',')
		# let's check to make sure that there really are 3 pieces (which is
		# not true for any empty lines at the end, which should be ignored)
		if len(pieces)==3:
			# try converting the second piece into an integer, but fail gracefully if not possible
			try:
				age=int(pieces[1])
				total_age+=age
				numdata+=1
			except:
				pass # "pass" is a Python keyword meaning "do nothing"
	return total_age/numdata