如何在包含字母和数字的.txt文件中查找平均值

时间:2015-09-18 19:22:30

标签: python file average

我制作了一个程序,应该询问用户是否需要文件中内容的平均值。用户可以选择三个文件。我的程序有其他选项,如按字母顺序排列最后结果,从最高到最低。当我将平均值添加到脚本时,它将说明以下内容:

ValueError: invalid literal for int() with base 10: 'g 2\n'

我认为这是因为str附加在文件中并带有结果。 我的代码:

elif viewhours==('hours a ave'): #If the users input is equal to hours a ave then the script will process the average.
    averageHours=[]#This is an empty list.
with open('hours a.txt') as f: #Opens the file, but manipulates it appending the contents inside.
   for line in f: #This part helps to analyse the lines in the file and wraps the code.
       if line.strip(): #This skips a blank line in the file and goes to another line.
          averageHours.append(int(line.strip()))
          #This outputs the average to the screen by appending it 

如何从文件中获取数字/结果,忽略文件中的字母以获得输出的平均值?

包含内容的文件:

bill 4

1 个答案:

答案 0 :(得分:2)

假设您的数据是以空格分隔的,可能的解决方案是:

import csv

data=[]

with open('data.csv', mode='r') as file:
    newfile = csv.reader(file, delimiter = ' ')
    for line in newfile:
        data.append(line[1])

您提供的输入文件:

clive 10
bill 4

现在data是一个包含该文件中数字的列表:

10
4
相关问题