I have to create a class of Persons that will hold information about their name,age,NI number.These details are read from a file that would look like :
55512 Bart Simpson 45
45622 John Smith 58
46231 Alicia Sands 27
My duty is to read each line from this file and supply it to the Person-creation function and store the result in a list.I've create the class and read all the line but I don't know how to store the ouput in list after the objects are created?So far my code is:

class Persons:
    def __init__(self,ni_number,name,age):
        self.__ni_number=ni_number
        self.__name=name
        self.__age=age

inFile = input("Specify input file: ")
f=open(inFile)
for line in f.readlines():
    pers=Persons(line[0],line[1],line[-1])

Recommended Answers

All 6 Replies

You've got the right idea but I think you're doing something you don't want to do and I know you're doing something wrong.

First the wrong thing.
When you read each line, for line in f.readlines():, "line" is a string. Strings are iterable but each character is an element. So, line[0] for instance would be "5" in the case of the Bart Simpson record. To get what you want you need to split the line into words (splitting on spaces): line=line.strip('\n').split(), also taking off the linefeed. Now you have another problem, the "name" field is 2 words, line[1] and line[2]. If you know both names are always going to be present then you can use the constructor: Persons(line[0], line[1]+' '+line[2], line[-1]). Otherwise you'll need to check on how many elements line has 4 or 3 and construct the object accordingly.

Now the other thing. In your loop, you keep using the same object name, "pers". Once the loop is done, you'll only have a single object. There are lots of ways to keep all the people "alive" but I think the best is to have a dictionary of people, dctPerson={}, and instead of "pers" use dctPerson[line[0]]=Persons(line[0], line[1]+' '+line[2], line[-1]).

You could also use a list of instances of class Persons like shown in the example here:

# format: ni_number firstname lastname age
data_str = '''\
55512 Bart Simpson 45
45622 John Smith 58
46231 Alicia Sands 27
'''

fname = "data123.txt"

# write test data file
with open(fname, "w") as fout:
    fout.write(data_str)



class Persons:
    def __init__(self, ni_number, name, age):
        self.__ni_number = ni_number
        self.__name = name
        self.__age = age

    def show(self):
        '''for a quick test'''
        # formating string
        sf = " ni_number = {}\n name = {}\n age = {}\n"
        return sf.format(self.__ni_number, self.__name, self.__age)


# read the data file back in and process
with open(fname, "r") as fin:
    person_list = []
    for line in fin:
        mylist = line.split()
        print(mylist)  # test
        # unpack the list
        ni_number, first, last, age = mylist
        name = first + ' ' + last
        # create a list of instances of class Persons
        person_list.append(Persons(ni_number, name, age))

print('-'*20)
# test one of the instances
inst1 = person_list[0]
print(inst1.show())


''' console output -->
['55512', 'Bart', 'Simpson', '45']
['45622', 'John', 'Smith', '58']
['46231', 'Alicia', 'Sands', '27']
--------------------
 ni_number = 55512
 name = Bart Simpson
 age = 45

'''

thank you guys I've got it now..I dunno how to thank you enough :)

I am glad you are using the __private option.

Guys sorry to disturb you again but after I've created my class with containing people's details as object,I need to display only those people that have a particular NI number. The code that I've tried keeps telling me that the class doesn't have the specified attribute.

nino=int(input('Please enter the Ni number'))
for p in person_list:
    if p.ni_number==nino:
        p.show()

What am I doing wrong?Thank you again in advance.

If you want to use a class attrribute, don't make it private with the double underline prefix. Also make sure that ni_number is an integer, if you want to use it as such. Here is the corrected code example:

# format: ni_number firstname lastname age
data_str = '''\
55512 Bart Simpson 45
45622 John Smith 58
46231 Alicia Sands 27
'''

fname = "data123.txt"

# write test data file
with open(fname, "w") as fout:
    fout.write(data_str)



class Persons:
    def __init__(self, ni_number, name, age):
        self.ni_number = int(ni_number)
        self.name = name
        self.age = int(age)

    def show(self):
        '''for a quick test'''
        # formating string
        sf = " ni_number = {}\n name = {}\n age = {}\n"
        return sf.format(self.ni_number, self.name, self.age)


# read the data file back in and process
with open(fname, "r") as fin:
    person_list = []
    for line in fin:
        mylist = line.split()
        print(mylist)  # test
        # unpack the list
        ni_number, first, last, age = mylist
        name = first + ' ' + last
        # create a list of instances of class Persons
        person_list.append(Persons(ni_number, name, age))

print('-'*20)
# test one of the instances
inst1 = person_list[0]
print(inst1.show())
print('-'*20)


#nino=int(input('Please enter the Ni number'))
nino = 45622  # test only
for p in person_list:
    if p.ni_number == nino:
        print("{} = {}".format(p.ni_number, p.name))


''' console output -->

['55512', 'Bart', 'Simpson', '45']
['45622', 'John', 'Smith', '58']
['46231', 'Alicia', 'Sands', '27']
--------------------
 ni_number = 55512
 name = Bart Simpson
 age = 45

--------------------
45622 = John Smith

'''
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.