这是我拥有的文本文件:
#EMP_NO, EMP_NAME, AGE, POSITION, SALARY, YRS_EMP
001, Peter Smyth, 26, Developer, 29000, 4
002, Samuel Jones, 23, Developer, 24000, 1
003, Laura Stewart, 41, DevOps, 42000, 15
004, Paul Jones, 24, Analyst, 21000, 2
005, Simon Brown, 52, Developer, 53000, 18
006, George Staples, 42, Tester, 42000, 12
007, Greg Throne, 57, DevOps, 50000, 23
008, Aston Bently, 27, Tester, 33000, 5
009, Ben Evans, 32, DevOps, 38000, 2
010, Emma Samson, 23, DevOps, 22000, 1
011, Stephanie Beggs, 43, Tester, 19000, 9
012, Sarah McQuillin, 47, DevOps, 23000, 5
013, Grace Corrigan, 48, Analyst, 44000, 16
014, Simone Mills, 32, DevOps, 32000, 11
015, Martin Montgomery, 28, Analyst, 28000, 3
我需要获取所有薪水并将其加在一起,但是我只能得到整条线,任何想法如何在python 3中做到这一点?
答案 0 :(得分:1)
f = open('nameoffile.txt') #open file
sum = 0 #initialise
i = 0
for line in f: #read each line from file
line = line.split(',') #read line as string, split to list of strings at the commas
if(i>0): #to disregrad the first line that is the header
sum += float(line[-2]) #salary is second from last, convert string to float to add
i += 1
print("Sum = ", sum)