在for循环之后,将Python字典写入csv文件



下面的代码旨在从在线数据库请求嵌套的json数据集,并只提取我需要的信息。我可以打印结果,所以它基本上有效。但是,我不知道如何将这些结果写在.csv文件中。恐怕我不能提供一个最小工作示例,因为这意味着要暴露我的登录名和密码。然而,任何关于我如何做到这一点的帮助都将是最受欢迎的,因为我是一个初学者。


# returns JSON object as a dictionary
json_complete = json.load(f)
# retrieves specific data
for i in json_complete['data']:
# documentId=i['documentId']
if i['topics'] != None:
for x in i['topics']:
documentId=x['documentId']
placeCited=x['topicPlaceName']
year=i['date']['docYear']
month=i['date']['docMonth']
day=i['date']['docDay']
documentDate=str(year)+ "-" + str(month)+"-" + str(day)

print(str(documentId) + ',' + placeCited + ','+ documentDate + ',') 

这是我得到的输出片段:

57217,Iran / Asia / World / Top of the TGN hierarchy,1561-7-26,
57217,Halab / Halab / Suriyah / Asia,1561-7-26,
57224,Istanbul / Istanbul / Marmara / Turkiye,1561-8-8,
57224,Iran / Asia / World / Top of the TGN hierarchy,1561-8-8,
57224,Halab / Halab / Suriyah / Asia,1561-8-8, 

我希望得到一个标题如下的csv:

'DocumentID', 'Place', 'Date'

使用csv库。https://docs.python.org/3/library/csv.html

import csv
file = open("file.csv", 'w', newline = "")
csvwriter = csv.writer(file)
csvwriter.writerow(['DocumentID', 'Place', 'Date'])
for i in json_complete['data']:
# documentId=i['documentId']
if i['topics'] != None:
for x in i['topics']:
documentId=x['documentId']
placeCited=x['topicPlaceName']
year=i['date']['docYear']
month=i['date']['docMonth']
day=i['date']['docDay']
documentDate=str(year)+ "-" + str(month)+"-" + str(day)
csvwriter.writerow([documentId, placeCited, documentDate])
file.close()

这将完成工作。希望能有所帮助。

试试这个。

json_complete = json.load(f)
with open("test.csv") as file:
file.write('DocumentID, Place, Daten') # write the header from in file.
# retrieves specific data
for i in json_complete['data']:
# documentId=i['documentId']
if i['topics'] != None:
for x in i['topics']:
documentId=x['documentId']
placeCited=x['topicPlaceName']
year=i['date']['docYear']
month=i['date']['docMonth']
day=i['date']['docDay']
documentDate=str(year)+ "-" + str(month)+"-" + str(day)

file.write(str(documentId) + ',' + placeCited + ','+ documentDate+'n') # write the data row to file

相关内容

  • 没有找到相关文章

最新更新