【问题标题】:How to get certain values from a text file in python 3如何从python 3中的文本文件中获取某些值
【发布时间】:2018-11-13 16:13:55
【问题描述】:

这是我的文本文件:

#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 中做到这一点?

我试图从以下问题中得到答案,但这无法对我的代码产生影响:Tried Question

【问题讨论】:

标签: python python-3.x file csv


【解决方案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)

【讨论】:

  • 你好。您的答案需要更多关于代码如何工作的解释才能成为一个好的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-06
  • 1970-01-01
  • 2016-04-20
  • 2020-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多