2016-09-17 51 views
0

我遇到了计算文件中数字平均值的问题。 到目前为止,我已经做了一个函数,读入文件并计算行数。 该文件由多列数字组成,但列8是我需要计算的列。计算文件中数字的平均值

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)) 

这些数字也是小数,所以我使用浮点数。

这是我的计算总和的数字, 应除以行数,但我来了一个错误,因为第一行是文本。

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

有没有办法让我的Python可以忽略第一行,只专注于下面的数字?

+0

没有得到你的问题,你想在文件或文件只是数字来计算的“行”数的平均值? –

+0

只是为了说清楚我想计算数字的平均值 –

回答

0

你可以使用txt.readline()读的第一线,但随着迭代的方式做到这一点坚持,刚落上使用文件迭代的第一行与next

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: 
     ... 

边注:这也是非常有用的跳过使用csv模块打开的文件的标题行,这是因为csv标题可以位于多行,因此next优于readline

0

试试这个

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)