将2D数组(对象)存储到文本文件中

问题描述 投票:0回答:2
CustomerList = []
CustomerList.append (c1)
CustomerList.append (c2)
CustomerList.append (c3)
CustomerList.append (c4)
CustomerList.append (c5)

for c in CustomerList:
    print ("%8s %25s %35s %15s %15s" % (c.name, c.birth, c.address, c.hkid, "$"+str(c.balance)+"HKD"))

我上面存储了c1-5值,所以我得到了结果

Jack    Jan, 10th, 1996  430 Davis Ct., San Francisco     M8875895       $40000HKD
Smith  March 24th, 1997  3-5 Tai Koo Shing, Hong Kong     M3133242         $600HKD
Suzy      May 5th, 1995 32 Clearwater Bay Ave. Hong Kong  M8378644      $100000HKD

我是这样的。

我想使用文件访问将此信息存储到文本文件中。

我试图做的是使用

inputFile = open("Customer.txt","w")
inputFile.write (....)

我不知道我应该如何包含在......空白中。

python file access file-handling
2个回答
1
投票
with open("Customer.txt","w") as f: #closes file automtically after loop ends
   for c in CustomerList:
     f.write("%8s %25s %35s %15s %15s \n" % (c.name, c.birth, c.address, c.hkid, "$"+str(c.balance)+"HKD"))

0
投票

用write替换print语句,然后写一个换行符然后关闭该文件

inputFile = open("Customer.txt","w")

for c in CustomerList:
  inputFile.write("%8s %25s %35s %15s %15s" % (c.name, c.birth, c.address, c.hkid, "$"+str(c.balance)+"HKD"))
  inputFile.write('\n')

inputFile.close()
© www.soinside.com 2019 - 2024. All rights reserved.