如何将已读入列表的文本文件的全部内容解析到类中?

2024-04-23 08:57:30 发布

您现在位置:Python中文网/ 问答频道 /正文

from itertools import islice
class Person(object):
    def __init__(self, social, firstName, lastName, dateOfBirth, State):
        self.social = social
        self.firstName = firstName
        self.lastName = lastName
        self.dateOfBirth = dateOfBirth
        self.State = State
    def tenPeople(self):
        for i in range(10):
            #print(self.social)
            print('{}  {}  {}  {}  {}'.format(self.social, self.firstName, self.lastName,self.dateOfBirth,     self.State))
            break
count = 0
with open('text.txt', 'r') as f:
    for line in f:
        person = f.readline()
        person = person.split()
         #parse the split contents of file to class Person
        person = Person(person[0], person[1], person[2], person[3], person[4])

        person.tenPeople()
        count+=1
print(count)

我的文件有1000行文本,但是,count只显示for循环迭代了500次。当我打印count时,它显示500。如何计算文本文件中的所有行。另外,如何使def tenPeople(self)只打印10行,而不是文件中的500行


Tags: inselffordefcountsocialfirstnameclass