-1

I want to extract information from csv file and for that want to create a "function" which can fetch info every time I call it for a particular "row". Below is my code but it return blank when I run it. Am I missing something here? thanks in advance

class person:
  def __init__(self,name):
    self.name = name

def importList():
  with open('attendees3.csv', 'r') as f:
    reader = csv.reader(f)
    return [person(name) for name in reader]
    
for person in importList():
  print(person.name)
TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • Does this answer your question? [How do I read and write CSV files with Python?](https://stackoverflow.com/questions/41585078/how-do-i-read-and-write-csv-files-with-python) – CATboardBETA Feb 07 '21 at 22:23

2 Answers2

3

It looks like you're most likely having trouble with the indentation in this code. Because of the indentation, what's happening is that you are defining the function "importList" within the class "person", and another problem is the code that's meant to call importList appears inside importList itself. The reason there's no output is because you're only declaring a class and not running any other code.

The code should probably look like:

import csv

class person:
  def __init__(self,name):
    self.name = name

def importList():
  with open ('attendees3.csv','r') as f:
    reader = csv.reader(f)
    return [person (name) for name in reader]

for person in importList():
  print(person.name)
  

I was able to run it with this example csv file content:

name
John Smith
Jane Smith
Bob Boblaw

And get the following output:

['name']
['John Smith']
['Jane Smith']
['Bob Boblaw']

I won't comment about other caveats, since I assume you're dealing with a simple bit of code under controlled circumstances.

Mark H
  • 4,246
  • 3
  • 12
1

Do you really have a CSV file, or just a file containing names? If the latter then you don't need to use csv.reader(), just read the file in the normal way.

If the former then the rows are returned as a list of strings, each string being one of the fields in the file. By default a comma separates the fields. You need to access the individual fields as required. Your code passes the whole row (a list) into the person constructor, so the value of member name will be that list, not the name as a string.

Assuming that there is only one field in the CSV file, row[0] will be that field in the row returned by the CSV reader. You can alter the function to access the first item in the row like this:

def importList():
    with open ('attendees3.csv', newline='') as f:
        reader = csv.reader(f)
        return [person(row[0]) for row in reader]

If you don't have a "real" CSV file, you can read it like this:

def importList():
    with open ('attendees3.csv') as f:
        return [person(line.strip()) for line in f]

This code simply reads each line, removes any leading and trailing whitespace, and creates person objects.

mhawke
  • 84,695
  • 9
  • 117
  • 138