3

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?

4
  • 1
    Side-note: for line in f.readlines(): is almost never needed; it forces the whole file to be slurped into a memory (in the form of a list of lines) before you can iterate it, making memory usage proportional to file size, rather than proportional to the size of the longest line in the file. Just use for line in f:, which produces lines lazily (file objects are lazy iterators of their own lines), beginning processing faster, keeping memory use down, and typically running faster (by virtue of not needing to construct and destroy the list at all). Commented Nov 12, 2021 at 19:28
  • Also, .replace("/n", '') is probably wrong; I'm guessing you're trying to remove trailing newlines (so you want "\n", not "/n") and it's unnecessary even then, since the .strip() is removing all leading and trailing whitespace (including newlines), and any given line can't have more than one newline (at the end, where .strip() would remove it). Commented Nov 12, 2021 at 19:30
  • it is getting them, they are just being overwritten by the next line each time. you have to do something with them on each iteration. It reads one line on each iter of the for loop. Commented Nov 12, 2021 at 19:32
  • Lastly, you probably want to use the csv module here; pipe-separated data can be handled by it just fine with minor dialect tweaks (and will handle appropriate escaping if the dialect is configured properly). It would simplify the code to: with open("students.txt", "r", newline='') as f: for name, age, grade in csv.reader(f, delimiter='|'): followed by whatever you actually do with name/age/grade. Commented Nov 12, 2021 at 19:32

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

Comments

2

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

8 Comments

@JohnByro solution is better. I saved author's code and added object creation.
This works, but I am unable to copy this list of students into another list as it somehow sees the entire list as a Student object?
How do you try to copy it? It can be copied just as any other list.
Every method that I try to use it says : "Student" object is not iterable
Student is a class. You should iterate through a list (in this code it is called students).
|
1
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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.