Home > Back-end >  How to create instances of an object with values from a .txt file
How to create instances of an object with values from a .txt file

Time:11-13

I would like to know how to take values and create instances of a an object ,with values for each instance taken from a line in a .txt file

I have a class called Student with values name, age and grade.

My code looks like this, but only takes values from the last line so I cannot create the classes.

class Student():

    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

with open("students.txt", "r") as f:
    for line in f.readlines():
    data = line.strip().replace("/n", '')
    name, age, grade = data.split("|")

Each line in the .txt looks like this:

John|19|94

How would I go about this? I'm grateful for all help.

CodePudding user response:

You can do in pythonic way

class Student:
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

    def __repr__(self):
        return f'{self.name}_{self.age}_{self.grade}'

with open("students.txt", "r") as f:
    # store record in list
    lines = [line.strip().split('|') for line in f]  

    # create object from records
    students = [Student(name, age, grade) for name, age, grade in lines]  
    print(students)

Assuming you have Student class created and have str/repr to print them

CodePudding user response:

You need to create an object on every iteration:

students = []

with open("students.txt", "r") as f:
    for line in f:
        data = line.strip().replace("/n", '')
        name, age, grade = data.split("|")
        s = Student(name, age, grade)
        students.append(s) # append object to list, for example

CodePudding user response:

class Student():
    def __init__(self, name, age, grade):
        self.name = name
        self.age = age
        self.grade = grade

students1 = []
with open("students.txt", "r") as f:
    for line in f.readlines():   
        data = line.strip().replace("/n", '')
        students1.append(Student(*data.split("|")))

    for stud in students1:
        print(stud.name   ' '   stud.age   ' '   stud.grade)
  • Related