使用CSV文件创建对象Python [英] Making objects from a CSV file Python
问题描述
我正在尝试创建一个Python对象的集合,其属性来自一个CSV文件。
I'm attempting to create a collection of objects in Python who's properties come from a CSV file.
目前,我有一个简单的类:
Currently, I have a simple class:
class myClass:
name = ""
age = 0
hobbies = []
def __init__(self, var1, var2, var3)
self.name = var1
self.age = var2
self.hobbies = var3
努力存储大量数据而不混乱代码,我创建了一个CSV文件,像这样:
In an effort to store a lot of data without cluttering the code, I've created a CSV file like so:
Robert Samson,50,swimming,biking,running
Sam Robertson,70,reading,singing,swimming
等等。我应该有大约50个,它们可能会改变,这是我使用CSV的原因。
and so on. I should have about 50 of these, and they may change, which is my reasoning for using CSV.
有没有办法从这个CSV文件系统地使myClass对象?我已经阅读你不应该尝试和使用唯一的名称在循环中的对象,但我不知道为什么。
Is there a way to systematically make myClass objects from this CSV file? I've read you shouldn't try and make objects with unique names in a loop but I'm not sure why.
感谢
编辑:我不是要找办法python中的csv数据,我需要创建对象...我的示例代码是一个有点误导,myClass具有我想要能够调用
I'm not looking for a way to store the csv data in python, I need to create objects... my example code is a little misleading in that myClass has functions that I'd like to be able to call
推荐答案
只需创建一个空列表,并向其中添加对象:
Just create an empty list and add the objects to it:
import csv
my_list = []
with open('file.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
my_list.append(myClass(row[0], row[1], row[2:]))
这篇关于使用CSV文件创建对象Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!