简体   繁体   English

读取带有数字的txt文件并将它们相加为python

[英]Reading txt file with number and suming them python

I have txt file witht the following txt in it: 我有txt文件,其中包含以下txt:

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 Thx提前

`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 返回3227

Open the file and use read() method to get the content and then convert string to int, use sum() to get the result: 打开文件并使用read()方法获取内容然后将字符串转换为int,使用sum()来获取结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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