Return specific column with csv library

Asked

Viewed 19 times

-1

I have a sheet with 4 columns and 2 rows and I want to return the column age, without the column identifier, only the contents of the rows.

Code:

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

for name in get_column_of_csv('teste.csv', 'sobrenome'):
    print(name)

Running the code displays this error:

Traceback (Most recent call last): File ... line 3, in from asyncore import file_wrapper Import: cannot import name 'file_wrapper' from 'asyncore' ... Does anyone know how to fix this mistake?

1 answer

0

Using this reference file as teste.csv:

    nome,sobrenome,idade,peso
    Maria,joao,20,60
    Joao,maria,10,30

Your code works normally by returning the column of surname.

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

    for name in get_column_of_csv('teste.csv', 'sobrenome'):
        print(name)

I suggest checking your indentation.

In your question you mentioned that you wish to display the age, then just change the selection criteria to age:

    for idade in get_column_of_csv('teste.csv', 'idade'):
        print(idade)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.