1

I've got a class Person which has attributes like name, age, weight, and height. I'm trying to add a function now which reads a CSV file that has these attributes for each person so it can print it out in the end, but I'm struggling to figure out how I can link those two.

So far I've written my read_people function at the bottom, but I don't know where to go from there. How can I link each part of each line to name, age, weight, and height?

"""File for creating Person objects"""

class Person:
    """Defines a Person class, suitable for use in a hospital context.
    Data attributes: name of type str
                     age of type int
                     weight (kg) of type float
                     height (metres) of type float
    Methods: bmi()
             status()
    """

    def __init__(self, name, age, weight, height):
        """Creates a new Person object with a specified name, age, weight, and
        height."""

        self.name = name
        self.age = age
        self.weight = weight
        self.height = height


    def bmi(self):
        """Returns the body mass index of the person"""
        return self.weight / (self.height * self.height)

    def status(self):

        if self.bmi() < 18.5:
            return "Underweight"
        if self.bmi() >= 18.5 and self.bmi() < 25:
            return "Normal"
        if self.bmi() >= 25 and self.bmi() < 30:
            return "Overweight"
        if self.bmi() >= 30:
            return "Obese"


    def __str__(self):
        """Returns the formatted string represent of the Person object"""
        name = self.name
        age = self.age
        bmi = self.bmi()
        status = self.status()
        template = "{0} ({1}) has a bmi of {2:3.2f}. Their status is {3}."
        return template.format(name, age, bmi, status)    




def read_people(csv_filename):

    file = open(csv_filename, "r")    
    for line in file:
        line = line.split(",")   



bods = read_people("people1.csv")
for bod in bods:
    print(bod)

Example of the csv file:

Peter Piper,23,89.4,1.82
Polly Perkins,47,148.8,1.67
Griselda Gribble,92,48,1.45
Ivan Ng,19,59,2.0
Lucy Lovelorn,14,50,1.6
Leslie McWhatsit,70,59.2,1.65
Mihai Chelaru
  • 7,614
  • 14
  • 45
  • 51
Amanda_C
  • 27
  • 7

3 Answers3

2

Try this:

def read_people(csv_filename):
    persons = []  # list for Person objects

    with open(csv_filename, "r") as file:  
        for line in file:
            args = line.split(",")

            for i in range(1, len(args)):  # convert arguments to float
                args[i] = float(args[i])

            persons.append(Person(*args))  # add Person objects to list
    return persons




bods = read_people("people1.csv")
for bod in bods:
    print(bod)
    print()

output:

Griselda Gribble (92.0) has a bmi of 22.83. Their status is Normal.

Ivan Ng (19.0) has a bmi of 14.75. Their status is Underweight.

Lucy Lovelorn (14.0) has a bmi of 19.53. Their status is Normal.

Leslie McWhatsit (70.0) has a bmi of 21.74. Their status is Normal.
Mahmoud Elshahat
  • 1,873
  • 10
  • 24
0

You are opening a file object in the 'file = open(cvs_filename, "r"). But you are not reading the file.

file = open(cvs_filename, "r")
file_contents = file.readlines()

Will read them into a list of lines to iterate, modify and capture in a different variable, then return the results to the caller.

Matt
  • 29
  • 5
0

Just make sure to cast the variables while creating the objects to make sure it works as expected


import csv

person_list = []

with open('file.csv', 'r') as f:
    reader = csv.reader(f)
    for row in reader:
        person_list.append(Person(row[0], int(row[1]), float(row[2]), float(row[3]))

razdi
  • 1,388
  • 15
  • 21