Home > Net >  How can i write my python code so that it sums the numbers from a .txt file?
How can i write my python code so that it sums the numbers from a .txt file?

Time:06-20

yeah so i have been working on this for hours and i can't get it to work. Sob story aside here is my code

numbers_file = open('numbers.txt', 'r')

#print(numbers_file.read())

for line in numbers_file():
    sum(line)

I left the "#print(numbers_file.read())" in there just to show my thinking.

Any input on how i can do this would be very nice.

Thanks

CodePudding user response:

Try

print(sum(map(float, open('numbers.txt').read().split())))

or

import pathlib
print(sum(map(float, pathlib.Path('numbers.txt').read_text().split())))

CodePudding user response:

Here is a simple solution that will work as long as the file contains only numbers (integers or floats), separated by whitespace (including newlines). (It's good practice to open files with a context manager, i.e., the with ... as part, as it closes the file automatically.)

total = 0

with open('numbers.txt', mode='r') as numbers_file:
    for number in numbers_file.read().split():
        total  = float(number)
  • Related