Need help finding average in this file (Python)
<p>I was given this file that opens up in excel which looks something like this:</p>

<pre><code>year interest inflation
1900    4.2      7.5
</code></pre>

<p>This goes on a lot further, all the way to 2008 if i remember right. We are suppose to write a function that accepts a single filename as a parameter and returns a list with 5 items. The first item is the average inflation rate. I just want to try and figure out this first one, and then maybe I'll better understand the other ones. I'm really new to programming so this is quite confusing. I'll show you what I wrote myself.</p>

<pre><code> def inflAvgMaxMin(file):
      file = open('thefilename', 'r')

      for line in file:
           print(line)
</code></pre>

<p>The 'thefilename' is not really what i put, but you know what i mean. So essentially all I was able to get done was being able to print the file in the interpreter. I just don't know where to start and how to write something to find the average inflation. Any suggestions?</p>

<p>Can you try this code?</p>

<pre><code>def inflAvgMaxMin(file):
      with open('thefilename', 'r') as f:
          inflation = []
          header = 1
          for line in f:
              if header != 1:
                  infl = line.split(",")[2]
                  inflation.append(float(infl))
                  header += 1

          avgInflation = sum(inflation)/len(inflation)    
     return avgInflation
</code></pre>

<p>It reads file line by line and get the inflation scores in each line and put it in a list and finally it calculates the average by dividing the sum by the number of elements in the list.</p>

<p><em>Detailed explanation:</em>
<code>with open(...) as f</code> means you open the file and name it as <code>f</code> which is a file handle object which can be used to read the lines and manipulate the file. <code>with</code> syntax automatically close the file and you don't have to do it explicitly.</p>

<p><code>line.split(",")</code> - split the line by comma; this will return a list; <code>line.split(",")[2]</code> means take the 3rd element in this list, which is the inflation score here. And finally you append it to a list; You do this for each line.</p>

<p>Once the for loop ends, you just calculate the average. And this function finally returns this value. </p>

<p><strong><em>Example:</em></strong></p>

<pre><code>In [12]: inflation = [1.1, 2.2, 3.2, 4.4, 5.5]

In [13]: avgInflation = sum(inflation)/len(inflation)

In [14]: avgInflation
Out[14]: 3.28
</code></pre>

python python-3.x average