5つの変数を持つ 'Student'クラスを使用し、複数のファイルを使用してオブジェクトを作成する必要があります。複数のファイルを使用してクラスからオブジェクトを作成するPython
テキストファイル:(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」を読んだとき、それは完璧に動作し、 first_name
、middle_name
、last_name
、およびstudent_id
というオブジェクトをStudent
というオブジェクトに作成します。しかし、私はまだオブジェクトにenrolled_courses
変数を追加し、 'EnrolledCourses.txt'から取得する必要があります。どのようにして両方のファイルを読み込み、作成しようとしているオブジェクトに変数を割り当てることができますか?