Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling from a txt to define something... Python

Tags:

python

So I have this class called Person, that basically has the constructor name, id, age, location, destination and what I want to do is that when I want to make a new person, I want it to open from a txt file.

For example, this is my Person Class (in the Module, People)

class Person :
    def __init__(self, name, ID, age, location, destination):
        self.name = name
        self.ID = ID
        self.age = age
        self.location = location
        self.destination = destination

    def introduce_myself(self):
        print("Hi, my name is " + self.name + " , my ID number is " + str(self.ID) + " I am " + str(self.age) + " years old")

import People

Fred = People.Person("Fred", 12323, 13, "New York", "Ithaca")

Fred.introduce_myself()

So basically, instead of me having to manually type that intializer "fred, 12232" etc.. I want it to read from a txt file that has all the things already written in.

This is what the txt file will have in it

[Name, ID, Age, Location, Destination]
[Rohan, 111111, 28, Ithaca, New Caanan]
[Oat, 111112, 20, Ithaca, New York City]
[Darius, 111113, 12, Los Angeles, Ithaca]
[Nick, 111114, 26, New Caanan, Ithaca]
[Andrew, 111115, 46, Los Angeles, Ithaca]
[James, 111116, 34, New Caanan, Ithaca]
[Jennifer, 111117, 56, Los Angeles, New Caanan]
[Angela, 111118, 22, New York City, Los Angeles]
[Arista, 111119, 66, New Caanan, Los Angeles]
like image 244
Panthy Avatar asked Oct 03 '22 14:10

Panthy


1 Answers

I'd use a JSON file, something like this:

cat people.json
[
 ["Rohan", 111111, 28, "Ithaca", "New Caanan"],
 ["Oat", 111112, 20, "Ithaca", "New York City"]
]

The code:

import json
with open('people.json') as people_file:
  for record in json.load(people_file):
    person = Person(*record) # items match constructor args
    person.introduce_myself()
like image 161
9000 Avatar answered Oct 07 '22 17:10

9000