-1

This is my code:

results = [[usernme, score]]

with open("hisEasyR.txt", "a") as hisEasyRFile:
        writer = csv.writer(hisEasyRFile, delimiter='|')
        writer.writerows(results)

This is what the text file looks like:

mary|4
john|5
ben|3

I want to take all the integers and calculate the average. For example, for this file, I would want it to output:

The average is 4. 

How would I go about doing this?

Programmer12
  • 73
  • 1
  • 10

3 Answers3

1

You could use list comprehension:

with open("hisEasyR.txt") as hisEasyRFile:
    numbers = [int(line.rstrip('\n').split('|')[-1])
               for line in hisEasyRFile if not line.isspace()]

print "The average is %d." % (sum(numbers) / len(numbers))
# The average is 4.
srikavineehari
  • 2,502
  • 1
  • 11
  • 21
0

The long way: Read line by line, use string split on the |. Then take the second string, (which is the number), and cast it to an int.

Refer to: https://www.tutorialspoint.com/python/string_split.htm

Pseudo:

sum = 0

For line in file:
     mySplit = str.split(line, '|')
     sum += int(mySplit[1])

avg = sum/numLines
Muska
  • 46
  • 5
0

In two lines: (assuming you already read the entire file to content)

new_list = [int(i.split("|")[1]) for i in content.split("\n") if "|" in i]
print "The average is " + str(sum(new_list) / float(len(new_list)))
Aviad Levy
  • 750
  • 4
  • 13