Harry Robinson Harry Robinson - 3 months ago 4
Python Question

Struggling to get a simple function running from command line

I'm trying to get the below function running from the command line by simply using

python filename.py

However, it isn't doing what I want.

Could someone please help me out with this? I'm sure I'm missing something very simple...

inFile = ""
inFile = raw_input("Enter the File Name: ")
x = open(inFile, 'w')

def summation(x):
sum = 0
for i in x:
sum = sum + i
return sum

if __name__ == "__main__":

Hopefully it's fairly self explanatory what I'm trying to achieve, but in case it's not...

I'm asking for a
; this will be a text file full of numbers (each on it's own line). The file should be fed into the variable
which is then used in the
function. Finally, with a for loop each value is summed and the sum is returned (and printed in terminal).


There are two problems:

  • You're opening the file in write mode. This deletes all the contents of the file. Drop the "w" parameter.
  • You can't add strings (as read from the file) to an integer. You need to convert them to integers first: sum += int(i)

Also, you should close the file after you've read its contents. And the line infile = "" is unnecessary.