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

标签 python file list exception

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

文本文件是

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/

相关文章:

java - 在 Java 中是否可以根据 Enum 中的另一个值多次将 Enum 的一个值添加到 Arraylist 中?

python - 转换为以行作为列表的普通数据框。将行拆分为列

python - Python-在两个.doc文件之间移动整个文本

linux - Perl:从 star 命令获取用户名和组名

css - 图像列表在 Internet Explorer 中被截断

java - StringBuilder.append 内存不足

c - 在C中编辑某个字符后的文件

python - 如何简化networkx图?

python - 为redis动态命名元组

python - 我正在使用 Hadoop 与 python 进行数据处理,应该使用什么文件格式?