我正在尝试将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行,因此与创建一个大数组并将其最终输出到文本文件相比,每次打开文本文件并写入输出都非常耗时吗?
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
这是您的初衷吗?
使用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)