从 CSV 文件 Python 创建对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24641894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Making objects from a CSV file Python
提问by ChuckDavis
I'm attempting to create a collection of objects in Python who's properties come from a CSV file.
我正在尝试在 Python 中创建一组对象,这些对象的属性来自 CSV 文件。
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
In an effort to store a lot of data without cluttering the code, I've created a CSV file like so:
为了在不弄乱代码的情况下存储大量数据,我创建了一个 CSV 文件,如下所示:
Robert Samson,50,swimming,biking,running
Sam Robertson,70,reading,singing,swimming
and so on. I should have about 50 of these, and they may change, which is my reasoning for using CSV.
等等。我应该有大约 50 个,它们可能会改变,这就是我使用 CSV 的原因。
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.
有没有办法从这个 CSV 文件系统地制作 myClass 对象?我读过你不应该尝试在循环中创建具有唯一名称的对象,但我不确定为什么。
Thanks
谢谢
EDIT: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
编辑:我不是在寻找一种在 python 中存储 csv 数据的方法,我需要创建对象......我的示例代码有点误导,因为 myClass 具有我希望能够调用的函数
采纳答案by user3557327
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:]))
回答by Roland Smith
Why not just use a dictionary?
为什么不直接使用字典?
import csv
persons = []
with open('file.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
persons.append({'name': row[0], 'age': int(row[1]),
'hobbies': row[2:]})