Get CSV list with Python

1

I have a CSV file with more than 9000 lines. I need to get a list with just one die from each line.

An example is as follows:

01/02/19,carlos,casa,rio
03/05/18,luis,carro,maceio
06/04/17,camila,celular,teresina

I need to get a list with just the names:

lista = ['carlos','luis','camila']

As close as I got to this code:

csvRows=[]
arq_contas = open ('C:.../lista_contas.csv')
leitura_contas = csv.reader(arq_contas,delimiter=',', lineterminator='\n')
for row in leitura_contas:
    csvRows.append(row[1:2])
    print(csvRows)

but I got the following result:

['carlos'], [], ['luis'], [], ['camila'], [],

I'm a beginner in Python and programming with a whole. So I need a light from you.

    
asked by anonymous 27.03.2018 / 02:57

2 answers

1

As you you have shown , the problem is that your CSV file is not formatted correctly, since there is a blank line between the records. Not that this invalidates, in fact, the format, but basically every blank line would be a null record, which would not make much sense.

From your code, the only fix needed to generate the desired result is to change row[1:2] to row[1] , because in the first way you would be taking two columns, not just one.

A slightly more elaborate solution would be:

import csv

def get_csv_column(filename, column):
    with open(filename) as stream:
        reader = csv.reader(stream)
        for row in reader:
            yield row[column]

print( list(get_csv_column('dados.csv', 1)) )

See working at Repl.it

27.03.2018 / 03:23
1

Good morning Anderson, thank you very much for the attention, but with your code the error continues:

IndexError: list index out of range

It's really a bug caused by CSV formatting, but I can not fix it.

Today I tested the code:

entrada = open('C:/...arquivo.csv','r')
saida = open('C:/...saida_arquivo.csv','w')
for linha in entrada:
    l = str(linha.split(','))
    saida.write(l)
entrada.close()
saida.close()

With this code I got the following:

['02/22/18', 'rosalvaponteatelierdecriacao', 'General', 'liked\n']['\n']['02/22/18', 'idealaeventobar', 'General', 'liked\n']['\n']['02/22/18', 'jasmim_wedding_trend', 'General', 'liked\n']['\n']
    
27.03.2018 / 13:52