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]
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With