我正在尝试制作一个将给定数量的JSON对象写入文本文件的python脚本。每个对象都必须位于自己的行上。
我希望能够循环X次,并且每次迭代该循环时,我都希望将JSON对象写入 utf8编码的文本文件。每个JSON对象将在其单独的行上。
import json
count = 5
while(count > 0):
data = {
"Address":[{
"Street":"Main St",
"State":"WY"
}],
"Name":"Jim",
"LastName":"Beam"
}
with open('data.txt', 'w') as outfile:
json.dump(data, outfile)
count = count -1;
这将继续覆盖整个文件,因此最终将文件覆盖5次。
我希望文件看起来像这样:
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
{"Address":[{"Street":"Main St", "State":"WY"}], "Name":"Jim", "LastName":"Beam"}
答案 0 :(得分:1)
每次循环时,它都会打开一个新文件,因此它将重写该文件,直到count> 0,因此必须有一个append方法将内容附加到现有文件中。