5

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]
karthikr
  • 97,368
  • 26
  • 197
  • 188
Panthy
  • 1,605
  • 4
  • 19
  • 27

7 Answers7

2

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()
9000
  • 39,899
  • 9
  • 66
  • 104
1

There are several ways to do this, the easiest being using standard file formats, like csv or serialisation, with JSON, for instance. I turns out that there are standard modules to do that.

An example with csv

import csv
with open('persons.csv', newline='') as f:
    dialect = csv.Sniffer().sniff(f.read(1024))
    f.seek(0)
    reader = csv.reader(f, dialect)
    for row in reader:
        This_Person = People.Person(*row)
        This.introduce_myself()

Your file being persons.csv and containing

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
…

As you can see, it is still very short, even using powerful modules, so please, don't resort to splitting lines for any non-trivial project. Trust me, I took the same path once and it was hard to recover from it.

Evpok
  • 4,273
  • 3
  • 34
  • 46
1
instances = {}         #use a dictionary to store the instances

#open the file using `with` statement, it'll automatically close the
#file for you
with open('abc') as f:
    next(f)                 #skip header
    for line in f:          #now iterate over the file line by line        
        data = line.strip('[]').split(', ')  #strip [] first and then split at ', '
        #for first line it'll return:
            #['Rohan', '111111', '28', 'Ithaca', 'New Caanan']  , a list object

        #Now we can use the first item of this list as the key 
        #and store the instance in the instances dict 
        #Note that if the names are not always unique then it's better to use ID as the
        #key for the dict, i.e instances[data[1]] = Person(*data)
        instances[data[0]] = Person(*data)  # *data  unpacks the data list into Person

#Example: call Rohan's introduce_myself
instances['Rohan'].introduce_myself() 

output:

Hi, my name is Rohan , my ID number is 111111 I am 28 years old
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
0

Take advantage of the splat operator and some string methods. Convert the text file into a list of lists using data = [list val for val in file.read().split('\n')] You can then call your constructor:

peopleList = []
for person in data:
       people.append(Person(*person))

peopleList will contain a list of person's created from your text file

If you wanted the people variables do be defined by name, you can use vars(), the dictionary containing all local variables. Then the code would be:

for person in data:
       vars()[str(person[0])]=Person(*person)
TheoretiCAL
  • 19,461
  • 8
  • 43
  • 65
  • 2
    The `vars()` trick is scary. It opens a door for all kinds of malicious code injection. Ask Little Bobby Tables. – 9000 Jul 10 '13 at 21:59
0

Try this:

people = {}
with open('file.txt', 'r') as f:
  data = [ l[1:-2].split(',') for l in f ][1:]
  for row in data:
      people{row[0]} = Person(*row)

people['Rohan'].introduce_myself()
jh314
  • 27,144
  • 16
  • 62
  • 82
0

import your text file into a list

with open(yourtextfile.txt) as peopleList:
  listOfPeople = peopleList.readlines()

you then can loop through the listOfPeople based on its length and run your function on each entry.

i'd recommend making it a json file though, will make it easier to phrase the data.

Dani
  • 1,220
  • 7
  • 22
0

You can use my shiny new poorly documented tsv module for "Tab-Separated Value" files, which you can get with:

pip install --user tsv

Then make a file with tab characters (not spaces) separating all your fields, and a # in front of informational comment lines:

# People file
# Name  ID  Age Location    Destination
Mary    10  45  Hither  Yon
Bob 11  22  Here    There

(Copy-pasting from here won't work; StackOverflow replaces tabs in answers with spaces.)

Then, read it in with something like:

import tsv
import People

for parts in tsv.TsvReader(open("people.txt")):
    # This gets run with "parts" holding a list of all the parts on each line.
    # If we don't care about having strings for ID and Age, we can just pass the
    # whle thing as the arguments to Person's __init__ by "dereferencing" the
    # list. See <http://stackoverflow.com/a/2921893/402891>

    People.Person(*parts).introduce_myself()

    # If you do care about type, it's a bit more complicated:
    People.Person(parts[0], int(parts[1]), int(parts[2]), parts[3], 
        parts[4]).introduce_myself() 
    # You might want to define some intermediate variables here for the sake of
    # good style.
interfect
  • 2,665
  • 1
  • 20
  • 35
  • The `csv` module can handle `tsv` files, too. or sv files with any separator for that matter. Why would you want another module? – Evpok Jul 11 '13 at 08:19
  • `tsv` supports comments, and has a simpler API. Also, I had the module lying around from a school assignment and I figured I'd upload it to PyPI. – interfect Jul 11 '13 at 16:31