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?
for line in f.readlines():is almost never needed; it forces the whole file to be slurped into a memory (in the form of alistof 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 usefor 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 thelistat all)..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).csvmodule 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 withname/age/grade.