Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 将数据从csv读入类对象列表-Python_Python 3.x_List_Class_Object - Fatal编程技术网

Python 3.x 将数据从csv读入类对象列表-Python

Python 3.x 将数据从csv读入类对象列表-Python,python-3.x,list,class,object,Python 3.x,List,Class,Object,我很难弄明白这一点。基本上,我有一个.csv文件,其中有7名员工,他们的名字和姓氏、员工ID、部门和职务。我的目标是让def readFileemployees接受名为employees的空列表,打开文件进行读取,并将文件中的所有员工加载到员工对象的列表中。我已经将我的类构建为: class Employee: def __init__(self, fname, lname, eid, dept, title): self.__firstName = fname self.__l

我很难弄明白这一点。基本上,我有一个.csv文件,其中有7名员工,他们的名字和姓氏、员工ID、部门和职务。我的目标是让def readFileemployees接受名为employees的空列表,打开文件进行读取,并将文件中的所有员工加载到员工对象的列表中。我已经将我的类构建为:

class Employee:
def __init__(self, fname, lname, eid, dept, title):
    self.__firstName = fname
    self.__lastName = lname
    self.__employeeID = int(eid)
    self.__department = int(dept)
    self.__title = title

我有几个其他的类方法,但基本上我不太明白如何正确地将文件加载到对象列表中。

为什么不使用pandas。因此,您可以定义一个employee对象,并使用其索引来选择每个员工,以及使用每个列的名称来选择特定的员工属性。

我能够理解这一点。我打开该文件,然后从中读取一行,剥离\n并拆分数据。我使用while循环来保持读行,只要它不是空行,并将它附加到我的空列表中。我还必须拆分第一个索引项,因为它是同一个字符串中的名字和姓氏,我需要将它们分开

def readFile(employees):
    with open("employees.csv", "r") as f:
        line = f.readline().strip().split(",")
        while line != ['']:
            line = line[0].split(" ") + line[1:]
            employees.append(Employee(line[0], line[1], line[2], line[3], line[4]))
            line = f.readline().strip().split(",")
它很可能写得更好,更像Python,但它做了我需要它做的事情