Python3 - getting the sum of a particular row from all the files [closed]

2024/10/10 12:23:24

I have many files in my directory of the below format:

name,sex,count
xyz,M,231
abc,F,654
...

i am trying to get the sum of count(3rd coloumn) for all files and store them in a list.

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

Any tips as to why my code doesn't work?

trying to get:

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

EDIT:

INPUT :

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

Here's code that works with the absolute bare minimum of modifications (that is, no style fixes were made):

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

The following had to be fixed:

  1. The result variable was set to zero only once, not once per file, so each new file read kept adding to the previous file's total. By my understanding you are trying to add the result from each file to the total list, so I moved this line to make that variable have the correct result.
  2. The line name, sex, count = line.split(',') is very fragile, whenever a line has a line without 2 commas in it (including the closing newlines), it would throw an error. I wrapped it in a try…except block that catches these errors and moves on to the next line when needed.
  3. The result was appended to the total list on every line read, not per file.

If I misinterpreted your intentions and you just wanted to keep a running total in the total variable for reference, you only need to make modification #2.

https://en.xdnf.cn/q/118454.html

Related Q&A

Selenium Headers in Python

how can I change my headers in Selenium like I do in requests ,I want to change my cookies and headers . from myCookie import cookie from selenium import webdriver from selenium.webdriver.common.by imp…

Get unique groups from a set of group

I am trying to find unique groups in a column(here for letter column) from an excel file. The data looks like this:id letter1 A, B, D, E, F3 B, C2 B75 T54 K, M9 D, B23 B, D, A34 X, Y, Z67 X, Y12 E, D15…

Move and Rename files using Python

I have .xls files in a directory that i need to move to another directory and renamed. Those files are updated monthly and will have a different name each month. For instance the current name is Geoc…

AttributeError: StringVar object has no attribute encode

Im making a program to generate an encrypted qr from the message and password provided, but it keeps on returning the same error.I tried passing the value to other variablesmain.pyfrom tkinter import *…

Reading specific column from a csv file in python

I am writing some python code to practice for an exam in January. I need to read the second column into my code and print it out. If possible i also need to add data to specific columns. The code i hav…

Date Time Series wise grouping of data and distribution

I am trying the merge the datetime series with a repository data while grouping by name and summing the values. File1.csv Timeseries,Name,count 07/03/2015 06:00:00,Paris,100 07/03/2015 06:00:00,Paris,6…

Trying to run Python in html

I am trying to run a python program in html but I am getting an error. First it says Then if I type anything it appears with this error This was the Html code <html><head><title>Antho…

Removing from a string all the characthers included between two specific characters in Python

Whats a fast way in Python to take all the characters included between two specific characters out of a string?

Pyside6: Create QTabWidget with function rather than class

Ive been trying to make an application using Pyside6 and cant seem to understand why we cant create a QDialog having QTabWidget with just functions. I am not sure if I am making a mistake somewhere so,…

Pythons End Of Life

What exactly will happen to Python 2.7 after 1/2020?I understand that Python 2.7 will no longer be supported but what will actually happen? Does it mean that decision makers will delete the whole cod…