简体   繁体   English

将列表转换为格式化的字符串,然后以所述格式将字符串写入文本文件

[英]Converting list to formatted string, then writing string to text file in said format

I need to convert a list into a string which I want to format as follows: 我需要将列表转换为想要格式化的字符串,如下所示:

Enter your Account Number: 1
l 0.0 l
2 0.0 2
3 0.0 3
4 0.0 4

I then want to write that string into a text file keeping the same format. 然后,我想将该字符串写入保持相同格式的文本文件中。

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()

If I print the string, it prints out in the right format, but only the last line of the string is written to the text file. 如果我打印字符串,它将以正确的格式打印出来,但是只有字符串的最后一行被写入文本文件。

Code: 码:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM