Reputation: 3
I currently have a textfile with saved data just as:
surname1
name1
number1
address1
surname2
name2
number2
address2
...
I want to use this textfile to create instances in my class:
class Contact(object):
def __init__(self, surname, name, number, address):
self.surname = surname
self.name = name
self.number = number
self.address = address
I need a function that can read from the textfile, use 4 rows as attributes for a new instance, append that instance to a list & then do it again for the next 4 rows and so on...how can this be done?
Upvotes: 0
Views: 1340
Reputation: 123463
Essentially each line of the input file represents the value of an attribute. You can mirror that in your code by reading the lines in groups and then pass those onto the Contact
class constructor.
Here's what I mean:
class Contact:
fields = 'surname', 'name', 'number', 'address'
def __init__(self, surname, name, number, address):
self.surname = surname
self.name = name
self.number = number
self.address = address
def __repr__(self):
return '{}({})'.format(self.__class__.__name__,
', '.join(getattr(self, field)
for field in self.fields))
filename = 'class_data.txt'
contacts = []
with open(filename) as file:
try:
while True:
fields = [next(file).strip() for _ in range(len(Contact.fields))] # Read group.
contacts.append(Contact(*fields))
except StopIteration: # end-of-file
pass
from pprint import pprint
pprint(contacts)
Output:
[Contact(surname1, name1, number1, address1),
Contact(surname2, name2, number2, address2),
Contact(surname3, name3, number3, address3)]
Upvotes: 0
Reputation: 3698
You can use more-itertools' sliced()
method to slice an iterable into equal chunks:
import more_itertools
contacts = []
class Contact:
def __init__(self, surname, name, number, addr):
self.surname = surname
self.name = name
self.number = number
self.addr = addr
with open('file.txt', 'r') as f:
content = f.read().split('\n')
for x in more_itertools.sliced(content, 4):
c = Contact(*x)
contacts.append(c)
Upvotes: 1