我有这个脚本从网页中抽象出json对象。 json对象被转换为字典。现在我需要在文件中编写这些词典。这是我的代码:
#!/usr/bin/python
import requests
r = requests.get('https://github.com/timeline.json')
for item in r.json or []:
print item['repository']['name']
文件中有十行。我需要在该文件中编写由十行组成的字典。我该怎么做?感谢。
答案 0 :(得分:5)
解决原始问题,例如:
with open("pathtomyfile", "w") as f:
for item in r.json or []:
try:
f.write(item['repository']['name'] + "\n")
except KeyError: # you might have to adjust what you are writing accordingly
pass # or sth ..
请注意,并非每个项目都是存储库,还有gist事件(等等?)。
更好的方法是将json保存到文件中。
#!/usr/bin/python
import json
import requests
r = requests.get('https://github.com/timeline.json')
with open("yourfilepath.json", "w") as f:
f.write(json.dumps(r.json))
然后,你可以打开它:
with open("yourfilepath.json", "r") as f:
obj = json.loads(f.read())