问题是逐行读取文件并计算并显示文件中所有有效数字的总和和平均值。
文本文件是
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
可能会帮助你入门
如果你想更聪明一点,有一个名为isdigit
的方便的Python函数,它检查字符串是否都是整数值,它可以让你做一些非常聪明的事情,比如:
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
关于Python:读取文件并计算总和和平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20960421/