1

I have a program that saves the scores you get in the program in a seperate file, however, the file saves the score as this:

2 4 6 8 9 8

My problem is that I cannot convert these to integers, so that I then can add them all together to a total sum.

This is as far as I have come:

scores = open("scores.txt", "r")

After that everything I have tried just ends up in different errors.

Anyone got any idea of what to do?

3
  • 2 4 6 8 9 8 in a single line space separated?? Commented Sep 9, 2015 at 11:40
  • given a string s, you need int(s) to make an int out of it Commented Sep 9, 2015 at 11:41
  • 3
    Can you give at least one example of what you have tried, and how it failed? Commented Sep 9, 2015 at 11:42

7 Answers 7

4

Do it as follows:

with open("scores.txt", "r") as f:
    score = f.read() # Read all file in case values are not on a single line
    score_ints = [ int(x) for x in score.split() ] # Convert strings to ints
    print sum(score_ints) # sum all elements of the list

37
Sign up to request clarification or add additional context in comments.

5 Comments

Tried it but it returns the error: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'
@Alepale weird, maybe then your values are not on the top line, use read instead (see EDIT).
@Alepale in case you have the same problem, print type(score) and check if it is a string, And make sure you respect the indents.
I am unsuire why it doesn't save as strings. This is the code that saves the score: guesses = str(guesses) scores.write(guesses) scores.write(" ") scores.close() but when I run print(type(scores)) I get: <class '_io.TextIOWrapper'>
@Alepale Something is wrong in your code, this should easily work, can you edit your question and provide a reproductible example?
2

This is how far I have come... "scores = open("scores.txt", "r")" After that everything I have tried just ends up in different errors. Anyone got any idea of what to do?

I would recommend splitting the string by delimiter.

You could do that by going line for line through the file.

for line in scores:
  splitted_line = line.split(' ')
  for values in splitted_line:
    value_as_int = int(values)
    # ... do something with value now

Another recommendation for scanning and handling large data is numpy in my opinion. There are several functions that will import data for you.

I can recommend for myself the genfromtext function. You can define filling values, delimiter and much more there.

Comments

1

You have to convert the scores (which are interpreted as Strings) to Integers.

s = "1"
i = int(s)

Comments

1

There are 2 ways to do this:

The first one is to assume that the other program outputs consistent positive integers with single-space delimiter. You can use this code:

with open('scores.txt', 'r') as f:
    lines = f.read(); 
    q = lines.split(' ')    
    a = sum(map(int, q))

print a

The second solution would be to use regex:

import re
intpattern = '[+-]?\d+'

with open('scores.txt', 'r')as f:
    lines = f.read(); 
    m = re.findall(intpattern, lines)
    a = sum(map(int, m))

print a

Comments

0

You convert to int by writing int(<variable>) e.g.

>>> a='3'
>>> type(a)
<type 'str'>
>>> a=int(a)
>>> type(a)
<type 'int'>

Comments

0

Try:

with open("scores.txt", "r") as f:
    for l in f;
        print(sum([int(a) for a in l.split()]))

Comments

-1

I cannot convert these to integers, so that I then can add them all together to a total sum (which in this case would be 2+4+6+8+9+8 = 37)

You can split a line, cast each string to integer, then sum all the numbers. You might as well store these sums in a list and calculate an average.

Try this:

sums = []
with open("scores.txt", "r") as f:
  for line in f:
    numbers = line.split() # 2 4 6 8 9 8
    s = 0
    for number in numbers:
        try:
            s += int(number)
        except:
            print 'can not cast to integer'
    sums.append(s)
  avg = sum(sums) / float(len(sums))

4 Comments

This assumes that all values are single digits, which is the case in the example, but an assumption nonetheless. Also it tries to convert the blanks between numbers into integers.
int (' ') generates the error: ValueError: invalid literal for int() with base 10: ''
This did the job, thank you! However, I then need to use this (sums) and divide it with another number to get the mean value. The whole point of the program is to take the scores + amount of times played, divide them with each other and then get the mean value out of it, then proceed to print that. I tried dividing it but I get the error: TypeError: float() argument must be a string or a number, not 'list'
@SemihYagcioglu Will do! Awesome job and thank you so much :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.