Python: Sum of numbers in a file
In this exercise we have a file called numbers.txt that has numbers in it and we need to sum the numbers.
examples/data/numbers.txt
3 7 23 0 -17 98 12
The following file has two solutions:
examples/python/sum_of_numbers.py
import sys if len(sys.argv) < 2: exit("Usage: {} FILENAME".format(sys.argv[0])) filename = sys.argv[1] total1 = 0 with open(filename) as fh: for line in fh: total1 += int(line) print(total1) with open(filename) as fh: total2 = sum(map(int, fh.readlines())) print(total2)
Published on 2020-01-17
If you have any comments or questions, feel free to post them on the source of this page in GitHub. Source on GitHub.
Comment on this post