[英]Trying to add object onto text file
我正在嘗試以有組織的方式將一堆對象上傳到文本文件中,但我不斷收到錯誤消息。 我不確定對象以及如何排列它們以便它們出現在文本文檔中。
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()
您不需要兩個循環來獲取每個 object 信息。 也許這就是你要找的。
def UpdateFile():
global allCustom
Outfile = open("CustomInfo.txt", "w")
for i in allCustom:
Outfile.write(f'\nName: {i.name}\n')
...
Outfile.close()
i
和c
是 integer 列表索引。 您不能使用c.name
,因為它不是Customer
object。 而且你不能索引i[...]
因為它不是一個容器。
您不需要嵌套循環,只需對所有客戶進行一個循環。 您的循環將i
從0
迭代到4
。 在第一次迭代中,它迭代 0 次,在第二次迭代中,它處理c == 0
,在第三次迭代中,它處理c == 0
和c == 1
等
然后,您可以使用格式化運算符將屬性放入要寫入文件的字符串中(我在下面使用了 f 字符串,但您也可以使用%
運算符或.format()
方法)。
def updateFile():
global allCustom;
with open("CustomInfo.txt", "w") as OutFile:
for c in allCustom:
OutFile.write(f"\nName:{c.name}\n")
OutFile.write(f"Birth Date:{c.date}\n")
OutFile.write(f"Address:{c.address}\n")
OutFile.write(f"HKID:{c.hkid}\n")
OutFile.write(f"Account value:{c.acc}\n")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.