Carl Carl - 7 months ago 13
Python Question

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()

Answer

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.