How to count the records of a csv in python?

0

I'm a beginner in Python and I'm having a hard time.

I have a separate CSV database for ";" with 6 columns. I'd like to count how many records they have, whose sex is "Female." Can you tell me how to do or where should I start my studies?

Below is the code I have so far.

import csv
with open('teste.csv', 'r') as arquivo:
delimitador = csv.Sniffer().sniff(arquivo.read(1024), delimiters=";")
arquivo.seek(0)
leitor = csv.reader(arquivo, delimitador)
dados = list(leitor)
for x in dados:
    print(x)

Converted to list, but I could not think of a way to check for "Female" on the line.

Any beginner tip will also be welcome.

    
asked by anonymous 16.10.2017 / 19:17

2 answers

1

To count the lines / lists that have "Female", you can do this:

import csv

l_feminino = []
with open('teste.csv', 'r') as arquivo:
    delimitador = csv.Sniffer().sniff(arquivo.read(1024), delimiters=";")
    arquivo.seek(0)
    leitor = csv.reader(arquivo, delimitador)
    dados = list(leitor)
for x in dados:
    if('Feminino' in x): # se existir 'Feminino'
        l_feminino.append(x) # vamos armazenar o registo

print(l_feminino) # todos os registos que tem "Feminino"
print(len(l_feminino)) # quantos registos que tem "Feminino"

You do not really need to import any modules for this, if that's all you can just:

dados = []
with open('teste.csv') as arquivo:
    lines = arquivo.read().split()
cols = lines.pop(0).split(';')
dados = [i.split(';') for i in lines]
dados_f = [i for i in dados if "Feminino" in i]
print(cols) # colunas
print(dados) # todos os registos
print(dados_f) # registos femininos
    
16.10.2017 / 19:32
0

To get the count of rows that have the "Female" occurrence in a particular file, you can do something like:

nlinhas = 0

with open('teste.csv') as arquivo:
    for linha in arquivo:
        if "Feminino" in linha:
            nlinhas += 1

print(nlinhas) 

Or simply:

nlinhas = sum( 1 for line in open('teste.csv') if "Feminino" in line )
print(nlinhas)
    
17.10.2017 / 03:35