[英]Converting list to formatted string, then writing string to text file in said format
我需要將列表轉換為想要格式化的字符串,如下所示:
Enter your Account Number: 1
l 0.0 l
2 0.0 2
3 0.0 3
4 0.0 4
然后,我想將該字符串寫入保持相同格式的文本文件中。
account= ["a1", "a2", "a3"]
balance= ["b1", "b2", "b3"]
names= ["n1", "n2", "n3"]
length = len(account)
i = 0
for i in range(i, length):
new_list = ''.format(account[i] + " " + balance[i] + " " + names[i])
print(new_list)
i += 1
string = new_list
data_file = open("bank.txt", 'a')
data_file.write(str(string))
data_file.close()
如果我打印字符串,它將以正確的格式打印出來,但是只有字符串的最后一行被寫入文本文件。
碼:
account= ["a1", "a2", "a3"]
balance= ["b1", "b2", "b3"]
names= ["n1", "n2", "n3"]
length = len(account)
data_file = open("bank.txt", 'w')
for i in range(length):
new_list = '{} {} {}\n'.format(account[i], balance[i], names[i])
data_file.write(new_list)
data_file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.