【问题标题】:I Would Like to Take the Average of All the Numbers in a Text File [duplicate]我想取一个文本文件中所有数字的平均值[重复]
【发布时间】:2020-02-19 05:29:33
【问题描述】:
def getFile():

    while True:
        try:
            fileName = input('Input a File Name: ')

            file = open(fileName, 'r')
            return file

        except IOError:
            print('Error, File Name Does Not Exist')

def readFile(file):

    sumTotal = 0
    count = 1

    line = file.readline()
    num = float(line)

    while line != ' ':
        sumTotal += num
        line = file.readline()
        num = float(line)
        count += 1
    avg = sumTotal / count
    return avg

def main():

    file = getFile()
    avg = readFile(file)

    print(avg)

    file.close()

main()

我想从文件中得到每个数字,如上图,并取所有的平均值。但是我继续收到错误,ValueError:无法将字符串转换为浮点数:。我有一条线显示我将文件中的字符串转换为浮点数。 任何帮助将不胜感激,谢谢。

【问题讨论】:

  • 是整个txt文件吗?也许有一条带空格的线?
  • 也许尝试将 line != ' ' 更改为 line != ''
  • 这不是整个文件,但我创建了一个只有几个数字的新文件,它给了我同样的错误。
  • 在浮点转换上方添加一个打印(行)。这应该让你看到字符串是什么并决定如何处理它
  • 它看起来只是将第一行作为字符串,但之后停止并显示错误。

标签: python python-3.x text-files valueerror readlines


【解决方案1】:

试试我的方法,用我的代码替换 def readFile(file)
下面的代码使用 with 作为上下文管理器打开并读取 testNum.txt,然后将字符串转换为列表中的 int。最后计算平均值。

with open("M:/Desktop/testNum.txt", 'r') as tf:
    list_ = [int(i) for i in tf.read().split()]
    print(sum(list_)/len(list_)) #returns average of all numbers in text file

【讨论】:

  • 如果文件中的值之一不是数字,您仍然会收到 ValueError(尽管可以说这比 OP 提供的极其冗长的代码更优雅)。
  • 是的,没错。这是假设所有值都是 TS 指定的数字。
猜你喜欢
  • 2014-05-07
  • 1970-01-01
  • 1970-01-01
  • 2020-09-24
  • 1970-01-01
  • 2017-08-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多