python - 试图将对象添加到文本文件中
问题描述
我正在尝试以有组织的方式将一堆对象上传到文本文件中,但我不断收到错误消息。我不确定对象以及如何排列它们以便它们出现在文本文档中。
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()
解决方案
您不需要两个循环来获取每个对象信息。也许这就是你要找的。
def UpdateFile():
global allCustom
Outfile = open("CustomInfo.txt", "w")
for i in allCustom:
Outfile.write(f'\nName: {i.name}\n')
...
Outfile.close()
推荐阅读
- python - HoughCircles 无法检测到这个圈子
- php - 如何在 Laravel 中按 ID 删除子文件夹?
- swift - 如何将一个pickerview用于多个文本字段?
- raspberry-pi - 从 can bus 读取消息并显示在树莓派网页上
- asp.net-core - 如何从 Blazor 的数据库中获取经过身份验证的用户
- javascript - 如何在 React State 中更新 Array 的奇异值
- javascript - Javascript 反引号字符串插值创建带有空格的 URL
- javascript - 无法写入 javascript 回调中的 textContent 属性
- python - 试图从多个 csv 文件制作数据帧 - UnicodeEncodeError: 'mbcs' codec can't encode characters in position 0--1: invalid character
- tcp - 计算 TCP 会话中发送的字节数