2016-11-21 77 views
0

我想所有这一切都通过逗号假设一个python文件(example.txt中)分离数之和数字的总和:包含喜欢的数字,号和返回所有

2,3,5,6,9 
1,5,6,9,4,5 
9,5 

回答

1

在Python中读取文件的标准方式是使用open(),然后使用read()readlines()。见例如here

要获取数字,您需要将分隔线分隔并将它们转换为int

最后sum()将总结列表中的所有元素。

#create an empty list to put numbers in 
a = [] 

#open file and read the lines 
with open("SO_sumofnumers.txt", "r") as f: 
    lines = f.readlines() 


for line in lines: 
    #split each line by the separator (",") 
    l = line.split(",") 
    for entry in l: 
     # append each entry 
     # removing line-end ("\n") where necessary 
     a.append(int(entry.split("\n")[0])) 

print a 
#sum the elements of a list 
s = sum(a) 
print s