2016-11-21 74 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