I am learning Python, need some pushing in the right direction
<p>I am trying to learn Python through Coursera, and have some questions about an assignment.</p>

<blockquote>
  <p>Write a program that prompts for a file name, then opens that file and reads through the file, looking for lines of the form:</p>

<pre><code>X-DSPAM-Confidence:    0.8475
</code></pre>
  
  <p>Count these lines and extract the floating point values from each of the lines and compute the average of those values and produce an output as shown below. Do not use the <code>sum()</code> function or a variable named <code>sum</code> in your solution.</p>
</blockquote>

<p>My code so far is as follows:</p>

<pre><code>fname = raw_input("Enter file name: ")
f = open(fname)
for line in f:
    if not line.startswith("X-DSPAM-Confidence:") : continue
    print line   
print "Done"
</code></pre>

<p>I am a bit confused. Should I store each line I get into a file or variable or something and then extract the floating point values for each?
How should this be tackled in the simplest way since this is just the beginning of the course?</p>

<p>Using <strong>Regular expression</strong>.</p>

<p><a href="https://pymotw.com/2/re/" rel="nofollow">More info regarding re module, check here !!!</a></p>

<p><strong>Code:</strong></p>

<pre><code>import re
fname = raw_input("Enter file name: ")
f = open(fname)
val_list = []
tot = 0
line_cnt = 0
for line in f:
  a = re.findall("X-DSPAM-Confidence:\s*(\d+\.?\d*)",line)
  if len(a) != 0:
    tot += float(a[0])
    line_cnt +=1

print ("Line Count is ",line_cnt)
print ("Average is ",tot/line_cnt)
f.close()
</code></pre>

<p><strong>Content of y.txt:</strong></p>

<pre><code>a
X-DSPAM-Confidence:    0.8475
b
X-DSPAM-Confidence:    0.8476
c
X-DSPAM-Confidence:    0.8477
d
X-DSPAM-Confidence:    0.8478
</code></pre>

<p><strong>Output:</strong></p>

<pre><code>C:\Users\dinesh_pundkar\Desktop&gt;python c.py
Enter file name: y.txt
Line Count is  4
Average is  0.84765

C:\Users\dinesh_pundkar\Desktop&gt;
</code></pre>

<p><strong>Points:</strong></p>

<ul>
<li><em>You can open file using <code>with</code> as Patrick has done in his answer. If file is opened using <code>with</code> then no need to close the file explicit.</em></li>
</ul>

python