D
D
danielsadovskiy2018-09-10 22:38:12
Python
danielsadovskiy, 2018-09-10 22:38:12

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)

To create an instance of the Person class, you need the Name, age, address,
how to implement such a function?
For example, I write in the file
Name Surname1: Age1: Adress1:
...
...
Name SurnameX: AgeX: Adress X:
So that I have X instances of the class?
Help me please)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton, 2018-09-10
@anttoon

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)

E
Eugene, 2018-09-11
@immaculate

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 question

Ask a Question

731 491 924 answers to any question