Stef Conovali
Stef Conovali

Reputation: 3

How to add numbers in an array stored in a file python

So I am trying to add numbers stored in a variable that is saved in a file.

if rw == "s":
    fo = open("foo.txt", "w")
    while int(count) != 0:
        x = input("Input a number for storage ")
        count = int(count) - 1
        test.append(int(x))
        print("")
    fo.write("%s" % test)
    fo.close()

fo = open("foo.txt", "r")
add = int(fo.readlines(1)) + int(fo.readlines(2))

I do not quite understand how the last part works. The error I get is the following:

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

The content of the file looks something like this: [6, 7, 8, 9, 5, 4, 3]

Any help would be appreciated

Upvotes: 0

Views: 355

Answers (1)

Robert F.
Robert F.

Reputation: 465

If you want to select the first and second value of the list and add them together do this

content = fo.readlines(1)
content = content[0].replace('[', '').replace(']', '')
numbers = content.split(", ")
add = int(numbers[0]) + int(numbers[1])

Explanation:

readlines reads all the lines in the file and returns a list. readlines(index) will return a list with only the selected line. Either case, you can't call int() on it.

Upvotes: 1

Related Questions