0

I am building a function that opens a file, calculates the sum of integers on different lines, and appends the file with a new string 'Total=sum' on a new line. I am getting error: can't assign to operator on my final value. This is not a duplicate being that I edited the way the duplicate suggestion did and it is still throwing an error. Also, I need to KEEP THE TOTAL, after every iteration.

Here is my function:

def append_total(filename):
    total=0
    with open(filename) as contents:
        for line in contents:
            if line.isdigit():
                total+=int(line)
            else:
                total=0
    final='Total:'+total+end='\n'
    contents.write(final)
    return 
kg123
  • 47
  • 9
  • You can't have keyword arguments to a tuple literal. – jonrsharpe Apr 12 '17 at 14:39
  • Possible duplicate of [Which is the preferred way to concatenate a string in Python?](http://stackoverflow.com/questions/12169839/which-is-the-preferred-way-to-concatenate-a-string-in-python) – Preston Martin Apr 12 '17 at 14:39
  • 1
    You should paste the exact error message as well! –  Apr 12 '17 at 14:40
  • @jonrsharpe can you elaborate? I'm new to this so I'm not sure what you mean – kg123 Apr 12 '17 at 14:43
  • 1
    `final = ('Total:', total, '\n')` would create a tuple, in the same way that `final = ['Total:', total, '\n']` would create a list. It's a *literal* form of that container. It cannot take a keyword argument like `end=`. – jonrsharpe Apr 12 '17 at 14:46
  • after every non-digit line `total` will be set to zero, previously accumulated sum will be lost, is it a desired behavior? – Azat Ibrakov Apr 12 '17 at 15:02
  • No. I want to keep the total @AzatIbrakov – kg123 Apr 12 '17 at 15:05

3 Answers3

2

There are several problems with your code.

1) statement

final = ('Total:', total, end='\n')

has invalid syntax and looks like you just removed print and replaced it with assignment to final. If you want to make string just write something like

final = 'Total:' + str(total) + '\n'

more info about string concatenation at docs

2) you are trying to write in file that was not opened in write mode and furthermore is closed after you leave with statement block. If you want to append a line in the end of existing file you can write

with open(filename, mode='a') as contents:
    contents.write(final)

more info about open at docs

3) you need to remove newline symbols from lines to make str.isdigit work as expected, we can do this by using str.strip method

line.strip().isdigit()

4) your accumulated total will be lost in cases when any line is not a digit-like, we can save it from zeroing just by removing else block

Finally your function will be like

def append_total(filename):
    total = 0
    with open(filename) as contents:
        for line in contents:
            stripped_line = line.strip()
            if stripped_line.isdigit():
                total += int(stripped_line)
    final = 'Total:' + str(total) + '\n'
    with open(filename, mode='a') as contents:
        contents.write(final)

(you don't need to explicitly return in the end of every function)

Azat Ibrakov
  • 9,998
  • 9
  • 38
  • 50
1

hey it seems to me that you have two "error" in your code:

first you try to write in a close file

second you don't open the file for writting or adding

def append_total(filename): total=0 with open(filename) as contents: for line in contents: if line.isdigit(): total+=int(line) else: total=0 with open (filename, 'a') as contents: # a for append w for write contents.write('Total:{}\n'.format(total))

` In python when a function return nothing you can spare the return statement Or if you want to be explicit say return None.

sorry didn't read all the comment but you also have a problem with total I updated my answer

RomainL.
  • 997
  • 1
  • 10
  • 24
1

There are several Problems with your script:

final=('Total:', total, end='\n')

The syntax error comes from end='\n'. You probably rewrote a print() line, but you cannot use that syntax when creating a tuple (which is what you do now).

A better version would be:

final = 'Total:' + total + '\n'

but that would fail, because you cannot "add" a string and an int.

You could use int(total), but using the format method would be even better:

final = 'Total: {}\n'.format(total)

The next problem is, that you try to write to the file after the with block, which will lead to another error. Move the last two lines into the block as well:

def append_total(filename):
    total = 0
    with open(filename) as contents:
        for line in contents:
            if line.isdigit():
                total += int(line)
            else:
                total = 0

    final = 'Total: {}\n'.format(total)
    contents.write(final)

This will still fail, because by default, files are opened read-only. You have to give open() a mode:

with open('blah.txt', 'r+') as contents:

will open the file read/writable and writes will be appended to the end (because you read the whole file before writing).

Further: the total will never be updated, because line contains a '\n' character at the end, and '1\n'.isdigit() will return False. You need to strip() the line before you use it:

line.strip().isdigit():

I also got rid of the final return, which is implicitely added by Python.