Carl
Carl

Reputation: 55

How do I add up total numbers in a text file for python?

I've been getting stuck in the total_num() function as it gives the error

"ValueError: invalid literal for int() with base 10: ''"

I know how to do it if its a defined list but if its set by the user I get confused.

def total_num():
    total = 0
    num_file = open("num_list.txt", "r")
    line = num_file.read()

    while line != "":
        num1 = int(num_file.readline())

        total = total + num1

    print total


def read_num():
    num_file = open("num_list.txt", "r")

    for line in num_file:
        print line.rstrip("\n")

def write_num():
    num = input("Enter a number: ")
    num_file = open("num_list.txt", "w")
    num_consec = 0

    for x in range(num):
        num_consec = num_consec + 1
        num_file.write(str(num_consec)+ "\n")

    num_file.close()

def main():
    write_num()
    read_num()
    total_num()


main()

Upvotes: 1

Views: 790

Answers (2)

TigerhawkT3
TigerhawkT3

Reputation: 49318

You are reading the file in an odd way - namely, twice. read() puts the entire file contents into a string. If you repeatedly check whether there are characters in it, and then never change it, it will either not execute or loop infinitely.

Using input() to get a number will work, but it's better to use raw_input() and cast with int() for safety. Also, xrange() is a better practice than range() in Python 2. You don't need to keep a manual counter if you're already iterating over range(), either.

Overall, your code could be condensed to this:

def write_num():
    num = int(raw_input("Enter a number: "))
    with open("num_list.txt", "w") as output:
    for x in xrange(1, num+1):
        output.write(str(x) + "\n")

def read_num():
    with open("num_list.txt") as f:
        numbers = map(int, f)
        for number in numbers:
            print number
        return numbers

def main():
    write_num()
    print sum(read_num())

main()

Upvotes: 0

e4c5
e4c5

Reputation: 53744

The error is because you are getting an empty string from your text file. Look at this bit of code; you are reading the whole file into memory.

line = num_file.read()

while line != "":

Over here, unless you opened an empty file line != "" you are comparing the whole file with an empty string. So you will keep on looping until your num1 = int(num_file.readline()) reads an empty line from the file.

You can find the solution if you look at your read_num method.

for line in num_file:
    try:
        total += int(line)
    except ValueError:
        print "Invalid data in ", line

By using try except you are able to handle the situation where the file might contain other invalid texts.

Upvotes: 1

Related Questions