【问题标题】:Looking for a way to write a dictionary to a csv in Python 3寻找一种在 Python 3 中将字典写入 csv 的方法
【发布时间】:2020-05-07 09:23:56
【问题描述】:

我正在尝试在线查找数据列表,并且我想将输出写入 csv 文件中的字典列表。 例如,我想将“结果”导出到 CSV

if resp.status_code == 200:
        soup = BeautifulSoup(resp.content, "html.parser")
        results = []
        for g in soup.find_all('div', class_='r'):
            anchors = g.find_all('a')
            if anchors:
                 link = anchors[0]['href']
                 title = g.find('h3').text
                 item = {
                "title": title,
                "link": link
                   }
                 results.append(item)
                 print(results)

【问题讨论】:

标签: python python-3.x pandas csv


【解决方案1】:

为什么不创建一个 DataFrame,将结果附加到它并将 DataFrame 导出到 .csv 文件?

df = pd.DataFrame(columns=['title', 'link'])

if resp.status_code == 200:
    soup = BeautifulSoup(resp.content, "html.parser")
    results = []
    for g in soup.find_all('div', class_='r'):
        anchors = g.find_all('a')
        if anchors:
            link = anchors[0]['href']
            title = g.find('h3').text
            df = df.append({'title' : title , 'link' : link} , ignore_index=True)

df.to_csv('output.csv')

【讨论】:

    【解决方案2】:

    这是一个例子。

    my_dict = {'1': 'aaa', '2': 'bbb', '3': 'ccc'}
    with open('test.csv', 'w') as f:
        for key in my_dict.keys():
            f.write("%s,%s\n"%(key,my_dict[key]))
    

    此代码将字典项写入 csv 文件,如下所示:

    1,aaa
    2,bbb
    3,ccc
    

    如果您尝试编写字典列表,您应该以“a”格式打开文件并为列表中的每个字典运行此文件。

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 2012-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      相关资源
      最近更新 更多