将Python字典转储到JSON文件 [英] Dump Python dictionary to JSON file

查看:316
本文介绍了将Python字典转储到JSON文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想转储我剪贴到json文件中的数据.我相信它已经采用了良好的格式(字典,列表,字符串等).如何输出到json文件中?

I want to dump data that i scrapped into a json file. I believe it already is in a good format (dictionary, list, string, etc.) How can I output into a json file?

#!/usr/bin/python
#weather.scraper

from bs4 import BeautifulSoup
import urllib
import json

    def main():
        """weather scraper"""
        r = urllib.urlopen("https://www.wunderground.com/history/airport/KPHL/2016/1/1/MonthlyHistory.html?&reqdb.zip=&reqdb.magic=&reqdb.wmo=&MR=1").read()
        soup = BeautifulSoup(r, "html.parser")
        tables = soup.find_all("table", class_="responsive airport-history-summary-table")

    scrapedData = {}
    for table in tables:
        print 'Weather Philadelphia'

        for tr in table.find_all("tr"):
            firstTd = tr.find("td")
            if firstTd and firstTd.has_attr("class") and "indent" in firstTd['class']:
                values = {}
                tds = tr.find_all("td")
                maxVal = tds[1].find("span", class_="wx-value")
                avgVal = tds[2].find("span", class_="wx-value")
                minVal = tds[3].find("span", class_="wx-value")
                if maxVal:
                    values['max'] = maxVal.text
                if avgVal:
                    values['avg'] = avgVal.text
                if minVal:
                    values['min'] = minVal.text
                if len(tds) > 4:
                    sumVal = tds[4].find("span", class_="wx-value")
                    if sumVal:
                        values['sum'] = sumVal.text
                scrapedData[firstTd.text] = values

    print scrapedData

    if __name__ == "__main__":
        main()

推荐答案

您需要使用以下内容:

with open('output.json', 'w') as jsonFile:
    json.dump(scrapedData, jsonFile)

要将字典写入工作目录中output.json文件的位置.
您可以提供完整的路径,例如open('C:\Users\user\Desktop\output.json', 'w')而不是open('output.json', 'w'),以将文件输出到用户的桌面.

Where is going to write the dictionary to the output.json file in the working directory.
You can provide full path like open('C:\Users\user\Desktop\output.json', 'w') instead of open('output.json', 'w') for example to output the file to the user's Desktop.

这篇关于将Python字典转储到JSON文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆