首页 > 解决方案 > 试图将对象添加到文本文件中

问题描述

我正在尝试以有组织的方式将一堆对象上传到文本文件中,但我不断收到错误消息。我不确定对象以及如何排列它们以便它们出现在文本文档中。

class Customer: 
    def __init__(self, name, date, address, hkid, acc):
        self.name = name
        self.date = date
        self.address = address
        self.hkid = hkid
        self.acc = acc

customer1 = Customer ("Sarah Parker","1/1/2000","Hong Kong, Tai Koo,Tai Koo Shing Block 22,Floor 10, Flat 1", "X1343434","2222")
customer2 = Customer ("Joe Momo","7/11/2002","Hong Kong, Tai Koo, Tai Koo Shing, Block 22, Floor 10, Flat 5", "C2327934","1234")
customer3 = Customer ("Brent Gamez","7/20/2002","Hong Kong, Tung Chung, Yun Tung, Block 33, Floor 10, Flat 9", "C1357434","2234")
customer4 = Customer ("Jose Gamez","7/20/2002","Hong Kong, Tung Chung, Yun Tung, Block 33, Floor 10, Flat 9", "C1357434","2234")
customer5 =Customer ("Viraj Ghuman","7/20/2002","Hong Kong, Heng Fa Chuen, 100 Shing Tai Road, Block 22, Floor 20, Flat 1", "C6969689","100000")
allCustom = [customer1, customer2, customer3, customer4, customer5]

def UpdateFile ():
    global allCustom
    OutFile = open("CustomInfo.txt","w")
    for i in range (len(allCustom)):
        for c in range (i):
            OutFile.write(allCustom[i["\n","Name:",c.name,"\n"]])
            OutFile.write(allCustom[i["Birth Date:",c.date,"\n"]])
            OutFile.write(allCustom[i["Address:",c.address,"\n"]])
            OutFile.write(allCustom[i["HKID:",c.hkid,"\n"]])
            OutFile.write(allCustom[i["Account value:", c.acc,"\n"]])
    OutFile.close()

标签: pythonarraysfileobjectprocedure

解决方案


您不需要两个循环来获取每个对象信息。也许这就是你要找的。

def UpdateFile():
    global allCustom
    Outfile = open("CustomInfo.txt", "w")
    
    for i in allCustom:
        Outfile.write(f'\nName: {i.name}\n')
        ...

    Outfile.close()

推荐阅读