使用Python计算.txt文件中的数字平均值

时间:2012-03-26 04:14:06

标签: python file python-3.x

def main():

    total = 0.0
    length = 0.0
    average = 0.0

    try:
        #Get the name of a file
        filename = input('Enter a file name: ')

        #Open the file
        infile = open(filename, 'r')

        #Read the file's contents
        contents = infile.read()

        #Display the file's contents
        print(contents)

        #Read values from file and compute average
        for line in infile:
            amount = float(line)
            total += amount
            length = length + 1

        average = total / length

        #Close the file
        infile.close()

        #Print the amount of numbers in file and average
        print('There were ', length, ' numbers in the file.' )
        print(format(average, ',.2f'))

    except IOError:
        print('An error occurred trying to read the file.')

    except ValueError:
        print('Non-numeric data found in the file')

    except:
        print('An error has occurred')


main()

这就是我的.txt文件中的数字出现的方式:

78
65
99
88
100
96
76

当我尝试运行时,我一直收到“发生了错误”。在我发表评论后,我得到了一个可分性错误。我试图打印出总数和长度,看看它们是否实际上是计算但是每个都是0.0,所以显然我在使它们正确积累方面存在一些问题。

3 个答案:

答案 0 :(得分:2)

infile.read()使用该文件。考虑在遇到它时写下每一行。

答案 1 :(得分:2)

infile.read()将获取整个文件,而不是单个部分。如果你想要单独的部分,你必须将它们拆分(按空格)并去掉空白(即\n)。

强制性单行:

contents = infile.read().strip().split()

然后,您希望迭代contents的内容,因为这将是值得迭代的唯一内容。 infile已经用尽,随后对read()的调用将生成一个空字符串。

for num in contents:
    amount = float(num)
    # more code here

 average = total / len(contents) # you can use the builtin len() method to get the length of contents instead of counting yourself

答案 2 :(得分:0)

我修改了你的代码,看看我是否可以让它工作,但仍然看起来和你的一样。这就是我想出的:

def main():

total = 0.0
length = 0.0
average = 0.0

    try:
        #Get the name of a file
        filename = raw_input('Enter a file name: ')

        #Open the file
        infile = open(filename, 'r')  

        #Read values from file and compute average
        for line in infile:
            print line.rstrip("\n")
            amount = float(line.rstrip("\n"))
            total += amount
            length = length + 1


        average = total / length

        #Close the file
        infile.close()

        #Print the amount of numbers in file and average
        print 'There were', length, 'numbers in the file.' 
        print format(average, ',.2f')

    except IOError:
        print 'An error occurred trying to read the file.' 

    except ValueError:
        print 'Non-numeric data found in the file'

    except:
        print('An error has occurred')

main()