python - Python3 - getting the sum of a particular row from all the files -


i have many files in directory of below format:

name,sex,count xyz,m,231 abc,f,654 ... 

i trying sum of count(3rd coloumn) files , store them in list.

total = [] result = 0 filename in os.listdir(direc):     if filename.endswith('.txt'):         file = open(direc + '/' + filename, 'r')         line in file:             line = line.strip()             name, sex, count = line.split(',')             if sex == 'f':                 result += int(count)                 total.append(result) 

any tips why code doesn't work?

trying get:

[sum(file1), sum(file2)...] 

edit:

input :

file1: xyz,m,231 abc,f,654  file2: wee,m,231 pol,f,654 bgt,m,434 der,f,543  file3: wer,f,432 uio,m,124 poy,f,783 

here's code works absolute bare minimum of modifications (that is, no style fixes made):

total = [] filename in os.listdir(direc):     result = 0     if filename.endswith('.txt'):         file = open(direc + '/' + filename, 'r')         line in file:             line = line.strip()             try:                 name, sex, count = line.split(',')             except valueerror:                 continue             if sex == 'f':                 result += int(count)     total.append(result) 

the following had fixed:

  1. the result variable set 0 once, not once per file, each new file read kept adding previous file's total. understanding trying add result each file total list, moved line make variable have correct result.
  2. the line name, sex, count = line.split(',') fragile, whenever line has line without 2 commas in (including closing newlines), throw error. wrapped in try…except block catches these errors , moves on next line when needed.
  3. the result appended total list on every line read, not per file.

if misinterpreted intentions , wanted keep running total in total variable reference, need make modification #2.


Popular posts from this blog