2

I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).

I have been attempting this problem for hours, and I have what is written below.

I do not know why my code does not seem to be summing up properly.

And the python code:

f=open("C:\\Users\\Emily\\Documents\\not_just_numbers.txt", "r")
s=f.readlines()
p=str(s)

for line in s:
    printnum=0
    try:
        printnum+=float(line)
        print("Adding:", printnum)    
    except ValueError:
        print("Invalid Literal for Int() With Base 10:", ValueError)

    for line in s: 
        if p.isdigit():
        total=0            
            for number in s:    
                total+=int(number)
                print("The sum is:", total)
3
  • can you expand more on what do you mean by the "code not summing properly"? Is the code throwing an error? Commented Mar 8, 2015 at 8:28
  • No error- but it is not summing at all. Commented Mar 8, 2015 at 8:30
  • As @davidruiz suggested, try .strip() method to remove newline characters. Try "float(line.strip())" instead of "float(line)" Commented Mar 8, 2015 at 8:32

8 Answers 8

8

I have a code that relies on me reading a text file, printing off the numbers where there are numbers, printing off specific error messages where there are strings instead of numbers, then summing ALL the numbers up and printing their sum (then saving ONLY the numbers to a new text file).

So you have to do the following:

  1. Print numbers
  2. Print a message when there isn't a number
  3. Sum the numbers and print the sum
  4. Save only the numbers to a new file

Here is one approach:

total = 0

with open('input.txt', 'r') as inp, open('output.txt', 'w') as outp:
   for line in inp:
       try:
           num = float(line)
           total += num
           outp.write(line)
       except ValueError:
           print('{} is not a number!'.format(line))

print('Total of all numbers: {}'.format(total))
Sign up to request clarification or add additional context in comments.

Comments

2

you can also try this:

f=open("C:\\Users\\Emily\\Documents\\not_just_numbers.txt", "r")
ww=open("C:\\Users\\Emily\\Documents\\not_just_numbers_out.txt", "w")
s=f.readlines()
p=str(s)


for line in s:
    #printnum=0
    try:
        #printnum+=float(line)
        print("Adding:", float(line))
        ww.write(line)
    except ValueError:
        print("Invalid Literal for Int() With Base 10:", ValueError)

total=0 
for line in s: 
    if line.strip().isdigit():
        total += int(line)
print("The sum is:", total)

here str.strip([chars]) means

Return a copy of the string with the leading and trailing characters removed. The chars argument is a string specifying the set of characters to be removed. If omitted or None, the chars argument defaults to removing whitespace. The chars argument is not a prefix or suffix; rather, all combinations of its values are stripped

Comments

2

This is a very short way to sum all numbers in your file (you will have to add try and except)

import re
print(sum(float(num) for num in re.findall('[0-9]+', open("C:\\Users\\Emily\\Documents\\not_just_numbers.txt", 'r').read())))

Comments

1

You are checking the wrong condition:

for line in s: 
    if p.isdigit():

p is this:

s=f.readlines()
p=str(s)

Being a strified version of a list, it will start with a '[', and hence p.isdigit() will always be false. You instead want to check line.isdigit(), and you want to only initialise total once instead of each time around the loop:

total = 0
for line in f:
    if line.isdigit():
        total += int(line)

Note that by iterating over f directly, you also don't need to ever call readlines().

Comments

1

Here is what you can do:

data.txt:

1
2
hello
3
world
4

code:

total = 0

with open('data.txt') as infile:
    with open('results.txt', 'w') as outfile:

        for line in infile:
            try:
                num = int(line)
                total += num
                print(num, file=outfile)
            except ValueError:
                print(
                    "'{}' is not a number".format(line.rstrip())
                )

print(total)


--output:--
'hello' is not a number
'world' is not a number
10


$ cat results.txt
1
2
3
4

1 Comment

You forgot to print an error message for non-numeric lines.
1

Every time you enter a new line you reset the total to zero if the number is a digit.

You might want your total to initialize before you enter the loop.


I tried debugging the for loop using the isdigit and isalpha apparently every new line is not considered a digit or alphanumeric these always evaluate to false

As it turns out you don't need the for loop you've done most of the program with your try except statement

Here's how I did it on my system.

f = open("/home/david/Desktop/not_just_numbers.txt", 'r')
s = f.readlines()
p = str(s)

total = 0

for line in s:
    #print(int(line))
    printnum = 0
    try: 
        printnum += float(line)
        total += printnum
        #print("Adding: ", printnum)
    except ValueError:
        print("Invalid Literal for Int() With Base 10:", ValueError)

print("The sum is: ", total)

3 Comments

tried moving the total=0 outside the loop. the function is still not summing the numbers
What is the program doing?
You might also want to print the sum after the for loop since you only need the final sum.
0
$ echo -e '1/n2/n3/n4/n5' | python -c "import sys; print sum(int(l) for l in sys.stdin)"

3 Comments

This may be a clever one-liner. But please add context and explanation. I don't think it does all that the OP asked for.
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
Really useful! You have forward slashes instead of backslashes. $ echo -e '1\n2\n3\n4\n5' | python -c "import sys; print sum(int(l) for l in sys.stdin)"
0

Read from file containing numbers separated by new lines:

    total = 0
    with open("file_with_numbers.txt", "r") as f:
        for line in f:
            total += int(line)
    print(total)

Comments

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.