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

2024-04-26 12:02:58 发布

您现在位置:Python中文网/ 问答频道 /正文

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,所以很明显,我在让它们正确累积方面遇到了一些问题。


Tags: ofthenameinmaincontentsfilenameamount
3条回答

我修改了你的代码,看看我是否能让它工作,仍然看起来尽可能像你的代码。这就是我想到的:

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()

infile.read()使用文件。当你遇到每一行的时候,考虑写下它。

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

相关问题 更多 >