Answer the question
In order to leave comments, you need to log in
Reading an instance of a class from a text file?
class Person:
def __init__(self,name = "n/a",age=0,adress="none"):
self.__name = name
self.__age = age
self.__adress = adress
inputfile = "human.txt"
outputfile = "persons.txt"
myfile1 = open(inputfile,mode="r")
myfile2 = open(outputfile,mode="w")
for num,line in enumerate(myfile1,1):
print("Line N:" + str(num) + "-> " + line.strip())
myfile2.write("Person: " + line)
Answer the question
In order to leave comments, you need to log in
If I understand correctly, I eventually created a dictionary of persons
class Person:
def __init__(self,name = "n/a",age=0,adress="none"):
self.__name = name
self.__age = age
self.__adress = adress
inputfile = "human.txt"
outputfile = "persons.txt"
myfile1 = open(inputfile,mode="r")
# myfile2 = open(outputfile,mode="w")
data = dict()
for num,line in enumerate(myfile1,1):
text_line = line.split(' ')
data['person '+ str(num)] = Person(name=text_line[0], age=int(text_line[2]), adress=text_line[3])
print(data)
I'd use a serialization package like serpy if it's a real project and not a school project, and pickle or shelve if it's a study project and there's no requirement to store it in plain text.
And one more thing: although the use of "private" variables with two underscores is considered good form in other OO languages, but in Python it is practically not used, and looks very "unpythonic". 99.9% of Python projects do not use any prefixes for class attributes.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question