[英]Python: Reading a file and calculating sum and average
问题是逐行读取文件,然后计算并显示文件中所有有效数字的总和和平均值。
文本文件是
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
使用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
让我们尝试使用try-except
列出理解。 这可能是一个矫kill过正的方法,但肯定是一个可以放在口袋中的好工具,首先,您需要编写一个使错误消失的函数,例如http://code.activestate.com/recipes/576872-exception-handling-in-a -单行/ 。
然后,您可以像在Unix中一样通过传入argv
来使用列表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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.