Python 3 - working with files -
i have 100+ files in directory each having 1000+ lines following format:
name,sex,number
for ex:
xyz,m,234
i need sum of number field files particular name occurs @ row 2 , sex 'f'. after checking condition code gives me sum of number field files in directory. here's code:
total = [] filename in os.listdir(direc): result = 0 if filename.endswith('.txt'): file = open(direc + '/' + filename, 'r') i, line in enumerate(file, 1): line = line.strip() name, sex, count = line.split(',') if 'xyz' == name , sex == 'f' , == 2: line in file: line = line.strip() name, sex, count = line.split(',') if sex == 'f': result += int(count) total.append(result)
what's wrong code. need sum of 3rd column sex = 'f' files where
'xyz' == name , sex == 'f' , == 2
well, starters, you're iterating on same file twice , mess results.
for i, line in enumerate(file, 1):
and
line in file:
part of problem here file object isn't list it's in memory -- it's iterator, , once @ line, it's gone. pull of lines memory list -- lines = list(file)
, check if second matches conditions -- 'xyz', 'f' == lines[1].split(',')[:2]
-- , act on whole list if it's true.
for single file:
with open(filename) f: lines = list(f) if 'xyz', 'f' == lines[1].split(',')[:2]: result = 0 line in lines: name, sex, count = line.strip().split(',') if sex == "f": result += int(count)