【问题标题】:Calculating average from numbers in .txt file using Python使用 Python 从 .txt 文件中的数字计算平均值
【发布时间】:2025-12-09 17:20:03
【问题描述】:
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,所以显然我在让它们正确累积方面遇到了一些问题。

【问题讨论】:

  • 如果你想弄清楚哪里出了问题,首先尝试not捕获异常,这样你就可以看到回溯。

标签: python file python-3.x


【解决方案1】:

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

【讨论】:

    【解决方案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
    

    【讨论】:

    • 之后代码已经正确地遍历了文件中的行;它只需要首先避免使用文件。
    • 这段代码有bug,应该是amount += float(num)
    【解决方案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()
    

    【讨论】: