我需要将列表转换为我想格式化的字符串,如下所示:
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()
如果我打印字符串,它会以正确的格式打印出来,但只会将字符串的最后一行写入文本文件。
答案 0 :(得分:1)
代码:
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()