0

So I am reading lines from a CSV, and trying to create class instances from those items. I am having problems getting the correct amount of parameters/formatting my str from the CSV so that it recognizes them as separate objects. It says that I have only given 2 parameters (self, and one of the rows) I tried using the split() and strip(), but can't get it to work. Any help would be appreciated. This has taken me way too long to figure out.

Here is an example of what the rows look like.

Current input:

whiskers,pugsley,Raja,Panders,Smokey
kitty,woofs,Tigger,Yin,Baluga

Current code:

import sys

class Animals:
    def__init__(self,cats,dogs,tiger,panda,bear)
        self.cats=cats
        self.dogs = dogs
        self.tiger = tiger
        self.panda = panda
        self.bear = bear

csv = open(file, 'r')
rowList = csv.readlines()
for row in rowList:
    animalList = Animals(row.split(','))  # Fails here...
    animals = []
    animals = animals.append(animalsList)  # Want to add to list
    print animals

1 Answer 1

1

You seem to have a couple syntax errors, I went ahead and corrected those. Next, I decided to use csv to split up the rows properly. And then, when your inputting a list to a function (and you want them to be parsed as arguments) you should use the * operator.

import sys, csv

file = "file.txt" #added for testing purposes.

class Animals:
    def __init__(self,cats,dogs,tiger,panda,bear):
        self.cats = cats
        self.dogs = dogs
        self.tiger = tiger
        self.panda = panda
        self.bear = bear

csv = csv.reader(open(file, 'r'))
animalsList = []
for row in csv:
    animalClass = Animals(*row)  # Fails here...
    animalsList.append(animalClass)  # Want to add to list
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.