python for循环将字符串追加到新行

时间:2020-03-18 16:21:36

标签: python append concatenation

我试图将for循环中的新信息附加到新行,然后将其写入文本文件。一个简单的示例代码给了我一些问题:

ID = "A1"
val = 0.4

tmp = []

for i in range(0,10):
    aa = (ID + ',' + repr(val))
    tmp.append(aa)

text_file = open("output.txt", "w")
text_file.write("%s\n" % tmp)

但是,“ output.txt”的内容是:

['A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4', 'A1,0.4']

我想让循环中的每个迭代都换行:

['A1,0.4'
'A1,0.4'
...
...
'A1,0.4']

我知道添加换行符'\ n'应该可以,但是只是将其添加为文本而不是换行符。其中一些文件的行长为1000行,因此与创建一个大数组并将其最终输出到文本文件相反,每次打开文本文件并写入输出都非常耗时吗?

2 个答案:

答案 0 :(得分:2)

使用join这样会更简单

ID = "A1"
val = 0.4

tmp = []

for i in range(0,10):
    aa = (ID + ',' + repr(val))
    tmp.append(aa)

data = '[{}]'.format('\n'.join(tmp))
text_file = open("output.txt", "w")
text_file.write(data)

答案 1 :(得分:1)

ID = "A1"
val = 0.4

tmp = []

for i in range(0, 10):
    aa = (ID + ',' + repr(val) + "\n")
    tmp.append(aa)

text_file = open("output.txt", "w")

for i in range(0, 10):
    text_file.write("{}".format(tmp[i]))

此代码产生以下输出:

A1,0.4
A1,0.4
...
A1,0.4

这是您的主意吗?