Python:读取文件并计算总和和平均值

时间:2014-01-06 22:22:16

标签: python file list exception-handling

问题是逐行读取文件并计算并显示文件中所有有效数字的总和和平均值。

文本文件是

contains text
79.3
56.15
67
6
text again 
57.86
6
37.863
text again 
456.675

到目前为止,这就是我所拥有的一切。

numbers = open('fileofnumbers.txt', 'r')

line = file_contents.readline()

numbers.close()

try:
    sum = line + line
    line = file_contents.readline()
    print "The sum of the numbers is", sum


except ValueError:
    print line

2 个答案:

答案 0 :(得分:2)

使用with表示法可以更直观地处理文件。

例如,将开始和结束更改为:

summation = 0

# Within the with block you now have access to the source variable
with open('fileofnumbers.txt', 'r') as source:
    for line in source: #iterate through all the lines of the file 
        try:
            # Since files are read in as strings, you have to cast each line to a float
            summation += float(line)
        except ValueError:
            pass

可能会让你开始

如果你想变得更聪明一点,有一个方便的python函数叫isdigit,它检查一个字符串是否都是整数值,这可以让你做一些非常聪明的事情:

is_number = lambda number: all(number.split('.').isdigit())
answer = [float(line) for line in open('fileofnumbers.txt') if is_number(line)]

然后使得总和和平均值变得微不足道:

print sum(answer) # Sum
print sum(answer)/len(answer) #Average

答案 1 :(得分:0)

让我们尝试使用try-except列表理解。这可能是一种矫枉过正,但肯定是一个很好的工具可以放在口袋里,首先你要编写一个能够在http://code.activestate.com/recipes/576872-exception-handling-in-a-single-line/中消除错误的功能。

然后你可以像在Unix中一样传递argv来使用列表理解:

intxt = """contains text
29.3423
23.1544913425
4
36.5
text again 
79.5074638
3
76.451
text again 
84.52"""

with open('in.txt','w') as fout:
    fout.write(intxt)

def safecall(f, default=None, exception=Exception):
    '''Returns modified f. When the modified f is called and throws an
    exception, the default value is returned'''
    def _safecall(*args,**argv):
        try:
            return f(*args,**argv)
        except exception:
            return default
    return _safecall

with open('in.txt','r') as fin:
    numbers = [safecall(float, 0, exception=ValueError)(i) for i in fin] 
    print "sum:", sum(numbers)
    print "avg:", sum(numbers)/float(len(numbers))

[OUT]:

sum: 336.475255142
avg: 30.5886595584
相关问题