python,json类型写入-如何对字典值使用\n?
我创建dic类型值,这是我的代码python,json类型写入-如何对字典值使用\n?,python,json,Python,Json,我创建dic类型值,这是我的代码 date = ["2015 1 3", "2015 1 3", "2015 1 3"] des = ["btcarchitect coinkite blockchain circlebits...", "swiftstealth offers you privacy in bitswift v2 ...", "all in one article bitcoin blockchain ..."] for i in range(3) : dic =
date = ["2015 1 3", "2015 1 3", "2015 1 3"]
des = ["btcarchitect coinkite blockchain circlebits...", "swiftstealth offers you privacy in bitswift v2 ...", "all in one article bitcoin blockchain ..."]
for i in range(3) :
dic = {"date":date[i], "description":des[i]}
with open('j.json', 'a', encoding='UTF-8-sig') as f:
f.write(json.dumps(dic, indent=2, ensure_ascii=False))
print (json.dumps(dic, indent=2, ensure_ascii=False) )
当我打印此值时,它可以正常工作,但如果写入此“dic”值,则每个元组上没有\n
这是打印结果(dic)
我的json文件是这样保存的
{
"date": "2015 1 3",
"description": "btcarchitect coinkite blockchain circlebits..."
}{
"date": "2015 1 3",
"description": "swiftstealth offers you privacy in bitswift v2 ..."
}{
"date": "2015 1 3",
"description": "all in one article bitcoin blockchain ..."
}
如何保存}和{?的结尾?您只需将
\n
添加到每行的结尾即可。以下是如何编写:
outputFile=open('somefile.txt','a')
for i in range(3) :
dic = {"date":date[i], "description":des[i]}
outputFile.write(json.dumps(dic) + '\n')
outputFile.close()
您只需将
\n
添加到每行的末尾即可。以下是如何编写:
outputFile=open('somefile.txt','a')
for i in range(3) :
dic = {"date":date[i], "description":des[i]}
outputFile.write(json.dumps(dic) + '\n')
outputFile.close()
尝试下面的方法。类似于《心理编码者》-
import json
date = ["2015 1 3", "2015 1 3", "2015 1 3"]
des = ["btcarchitect coinkite blockchain circlebits...", "swiftstealth offers you privacy in bitswift v2 ...", "all in one article bitcoin blockchain ..."]
with open('j.json', 'a') as f:
for i in range(3) :
dic = {"date":date[i], "description":des[i]}
f.write(json.dumps(dic, indent=2, ensure_ascii=False))
f.write("\n")
print (json.dumps(dic, indent=2, ensure_ascii=False) )
尝试下面的方法。类似于《心理编码者》-
import json
date = ["2015 1 3", "2015 1 3", "2015 1 3"]
des = ["btcarchitect coinkite blockchain circlebits...", "swiftstealth offers you privacy in bitswift v2 ...", "all in one article bitcoin blockchain ..."]
with open('j.json', 'a') as f:
for i in range(3) :
dic = {"date":date[i], "description":des[i]}
f.write(json.dumps(dic, indent=2, ensure_ascii=False))
f.write("\n")
print (json.dumps(dic, indent=2, ensure_ascii=False) )
f.write('\n')
?请不要包含代码的图片,最好是文本。但您试图创建的是JSON LinesTry删除indent=2
,只转储原始代码string@zvone它不起作用。@roganjosh我编辑了它。我如何创建新的json行?f.write('\n')
?请不要包含代码的图片,最好是文本。但您试图创建的是JSON LinesTry删除indent=2
,只需转储原始代码即可string@zvone它不起作用。@roganjosh我编辑了它。我怎样才能创建新的json行?