Python 通讯录练习I';I’我希望它拆分列表中的每一行,但只需要最后一行

Python 通讯录练习I';I’我希望它拆分列表中的每一行,但只需要最后一行,python,class,oop,for-loop,Python,Class,Oop,For Loop,作为练习,我必须实现一个地址簿,它必须能够读取包含联系人的文件的内容并执行CRUD(创建、读取、更新、删除)。我在地址簿方面遇到了一些问题,特别是init方法的定义。我认为在这个方法中,我应该放置属性(在本例中没有)和类必须执行的基本函数,以执行所需的函数(CRUD)。联系人位于txt文件中,因此类必须读取该文件并复制列表中的所有内容,以便能够修改它。所以我考虑过这段代码,但如果我打印联系人列表,它只返回最后一行。for循环似乎不起作用。我找不到错误 class Contact: d

作为练习,我必须实现一个地址簿,它必须能够读取包含联系人的文件的内容并执行CRUD(创建、读取、更新、删除)。我在地址簿方面遇到了一些问题,特别是init方法的定义。我认为在这个方法中,我应该放置属性(在本例中没有)和类必须执行的基本函数,以执行所需的函数(CRUD)。联系人位于txt文件中,因此类必须读取该文件并复制列表中的所有内容,以便能够修改它。所以我考虑过这段代码,但如果我打印联系人列表,它只返回最后一行。for循环似乎不起作用。我找不到错误

class Contact:  
    def __init__(self,name,surname,mail):
        self.name=name
        self.surname=surname
        self.mail=mail

    def __repr__(self):
        return"{},{},{}".format(self.name,self.surname,self.mail)

class AddressBook:    
    def __init__(self):
        File= open("contacts.txt").read()
        self.contacts=[]
        lines=File.splitlines()
        for line in lines:
            contact_section=line.split(',') 
        self.contacts.append(Contact(contact_section[0],contact_section[1],contact_section[2]))

AddressBook的问题是,您正在对这些行进行迭代 但您只将最后一个添加到列表中

def __init__(self):
    File= open("contacts.txt").read()
    self.contacts=[]
    lines=File.splitlines()
    for line in lines:
        contact_section=line.split(',') 
    # CHECK THE INDENTATION IS NOT INSIDE THE FOR LOOP
    self.contacts.append(Contact(contact_section[0],contact_section[1],contact_section[2]))

把电话拨到这条线上

self.contacts.append(Contact(contact_section[0],contact_section[1],contact_section[2]))
像这样的for循环内部

def __init__(self):
    File= open("contacts.txt").read()
    self.contacts=[]
    lines=File.splitlines()
    for line in lines:
        contact_section=line.split(',')
        self.contacts.append(
            Contact(contact_section[0],contact_section[1],contact_section[2])
        )

self.contacts.append(…)
应该在循环中一些额外提示
contact\u节[0],contact\u节[1],contact\u节[2]
可以替换为
*contact\u节
(假设每个节有3个条目)。您的文件打开/循环可能会更好一些:
将open(“contacts.txt”)作为fh:for-in-fh:
(当然要修正缩进)这使您在阅读文件时解析文件,而不是先阅读整个文件,然后再处理它。非常感谢您的提示!我没有注意到缩进错误