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>Try this</p>

<pre><code>import re
#regular expression for decimals
digits_reg = re.compile(r"\d+\.\d+|\d+")

with open('''file name''', "r") as file:
    allNum = []
    #find numbers in each line and add them to the list
    for line in file:
        allNum.extend(digits_reg.findall(line))

#should be a list that contains all numbers in the file
print(alNum)
</code></pre>

python file numbers