Calculate the average value of the numbers in a file
<p>I am having a problem of calculating the average value of numbers in a file.
So far i have made a function that reads in files and calculate the number of lines. 
The file consists of many columns of numbers, but the column 8 is the one i need to calculate from. </p>

<pre><code>def file_read():
     fname = input("Input filname: ")
     infile = open(fname,'r')
     txt = infile.readlines()
     print("opens",fname,"...")

num_lines = sum(1 for line in open(fname))

#The first line in the file is only text, so i subtract 1 
print("Number of days:",(num_lines-1))
</code></pre>

<p>The numbers are also decimals, so i use float.</p>

<p>This is my try on calculating the sum of numbers, 
which shall be divided by the number of lines  , but i comes an error, cuz the first line is text. </p>

<pre><code>with open(fname) as txt:
         return sum(float(x)
               for line in txt
               for x in line.split()[8]
</code></pre>

<p>Is there a way i can get python to ignore the first line and just concentrate about the numbers down under? </p>

<p>You could use <code>txt.readline()</code> to read the first line, but to stick with iterators way to do it, just drop the first line using iteration on file with <code>next</code></p>

<pre><code>with open(fname) as txt:
   next(txt)  # it returns the first line, we just ignore the return value
   # your iterator is now on the second line, where the numbers are
   for line in txt:
       ...
</code></pre>

<p>Side note: this is also very useful to skip title lines of files open with the <code>csv</code> module, that's where <code>next</code> is better than <code>readline</code> since csv title can be on multiple lines.</p>

python file numbers