简体   繁体   中英

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

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

Try

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

or

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

Both TextIOWrapper.read and Path.read_text return the contents of the file as a string. str.split split the string according to any whitespace. map applies a function float to every word. sum computes the total. The second version is more pedantic. It closes the file and uses an accurate floating point sum.

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, ie, 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)

print(total)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM