Python使用多个文件从类创建对象

时间:2016-10-19 20:24:36

标签: python file object

我需要使用带有5个变量的'Student'类,并使用多个文件创建对象。

文本文件:(Students.txt)

Last Name  Midle Name  First Name   Student ID  
----------------------------------------------
Howard                  Moe         howar1m     
Howard                  Curly       howar1c     
Fine                    Lary        fine1l      
Howard                  Shemp       howar1s     
Besser                  Joe         besse1j     
DeRita      Joe         Curly       derit1cj    
Tiure       Desilijic   Jaba        tiure1jd    
Tharen                  Bria        thare1b     
Tai         Besadii     Durga       tai1db     

文本文件2:(CourseEnrollment.txt)

PH03
----
fine1l
howar1s
besse1j
derit1cj
tiure1jd
targa1d
bomba1t
brand1m
took1p
mccoy1l
solo1h
edrie1m
mccoy1e
adama1l
grays1z

MT03
----
cottl1s
fine1l
clega1s
targa1d
took1p
mccoy1l
crush1w
dane1a
monto1i
rugen1t
talto1v
watso1j
carpe1m
rosli1l
biggs1gj
tigh1e

PH05
----
zarek1t
adama1w
tigh1s
cottl1s
howar1m
howar1s
besse1j
balta1g
derit1cj
thare1b
hego1d
lanni1t
stark1a
clega1s
scott1m
monto1i
flaum1e
watso1j
biggs1gj
dane1a

EN01
----
howar1c
fine1l
tai1db
targa1d
brand1m
corey1c
edrie1m
watso1j
carpe1m
sobch1w

EN02
----
howar1m
howar1s
besse1j
tiure1jd
tai1db
hego1d
lanni1t
stark1a
mccoy1l
scott1m
crush1w
dane1a
monto1i
rugen1t
solo1h
flaum1e
talto1v
watso1j
mccoy1e

CS02
----
howar1m
howar1c
besse1j
derit1cj
thare1b
hego1d
clega1s
targa1d
brand1m
rugen1t
flaum1e
talto1v
mccoy1e
grube1h

AR00
----
tigh1e
rosli1l
murph1a
grays1z
howar1c
howar1s
tiure1jd
thare1b
lanni1t
clega1s
bomba1t
balta1g
brand1m
took1p
crush1w
corey1c
edrie1m
grube1h
sobch1w

MT01
----
derit1cj
tai1db
hego1d
stark1a
bomba1t
took1p
scott1m
crush1w
grube1h
rugen1t
solo1h
corey1c
flaum1e
talto1v
mccoy1e
carpe1m
sobch1w

CS01
----
howar1m
howar1c
fine1l
tiure1jd
thare1b
tai1db
lanni1t
stark1a
bomba1t
mccoy1l
monto1i
solo1h
biggs1gj
corey1c
edrie1m
carpe1m

CS05
----
grays1z
adama1w
adama1l
rosli1l
balta1g
tigh1e
tigh1s
cottl1s
zarek1t
murph1a
sobch1w
dane1a

EN08
----
grays1z
adama1w
adama1l
rosli1l
balta1g
tigh1e
tigh1s
cottl1s
zarek1t
murph1a
grube1h
biggs1gj

OT02
----
adama1w
adama1l
tigh1s
scott1m
zarek1t
murph1a

我需要读取文本文件以使用文件和'Student'类创建Student对象。 课程是:

class Student (object):
    def __init__(self, first_name, middle_name, last_name, student_id, enrolled_courses):
        """Initialization method"""
        self.first_name = first_name
        self.middle_name = middle_name
        self.last_name = last_name
        self.student_id = student_id
        self.enrolled_courses = enrolled_courses

在主要方法中我有:

if __name__ == '__main__':
    list_of_students = []
    with open('Students.txt') as f:
        for line in f:
                data = line.split()
                if len(data) == 3:
                    first_name, last_name, student_id = data
                    list_of_students.append(Student(last_name, '', first_name, student_id))
                elif len(data) == 4:
                    list_of_students.append(Student(*data))
                else:
                    continue

当我在没有enrolled_courses变量的情况下运行程序并且仅在'Students.txt'中读取时,它运行完美并使用Studentfirst_name创建middle_name个对象,last_namestudent_id。但是,我仍然需要使用enrolled_courses变量添加到对象并从'EnrolledCourses.txt'获取它。如何读取这两个文件并将变量分配给我正在尝试创建的对象?

1 个答案:

答案 0 :(得分:1)

首先阅读您的学生/课程并创建字典:key = student,value =课程列表

格式很奇怪但是下面的代码已经过测试并且有效(尽管可能没有那么强大)。逐行阅读,首先阅读课程,并列出学生名单。添加到字典(如果键不存在则创建空列表,不错的defaultdict对象可以这样做):

from collections import defaultdict

student_course = defaultdict(list)
with open("CourseEnrollment.txt") as enr:
  while True:
    try:
        course_name = next(enr).strip()
        next(enr)  # skip dashes
        while True:
            student = next(enr).strip()
            if student=="":
                break
            student_course[student].append(course_name)
    except StopIteration:
        break

并在您的代码中,像这样调用Student构造函数:

list_of_students.append(Student(last_name, '', first_name, student_id, student_course[student_id]))