简体   繁体   中英

Reading txt file with number and suming them python

I have txt file witht the following txt in it:

2
4 8 15 16 23 42
1 3 5
6
66 77
77
888
888 77
34
23 234 234
1
32
3
23 23 23 
365
22 12

I need a way to read the file and sum all the numbers. i have this code for now but not sure what to do next. Thx in advance

`lstComplete = []
fichNbr = open("nombres.txt", "r")
lstComplete = fichNbr
somme = 0

for i in lstComplete:
    i = i.split()`

Turn them into a list and sum them:

with open('nombres.txt', 'r') as f:
    num_list = f.read().split()
    print sum([int(n) for n in num_list])

Returns 3227

Open the file and use read() method to get the content and then convert string to int, use sum() to get the result:

>>> sum(map(int,open('nombres.txt').read().split()))
3227

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