【问题标题】:How to append dict in to the csv file and excel file in python如何在python中将dict附加到csv文件和excel文件中
【发布时间】:2017-09-24 07:45:36
【问题描述】:

我在 python 中有 dict,我想将它附加到 CSV 文件和 Excel 文件中。

我有一个函数可以返回下面的字典

d = {'Engine': u'2.0 TSI MLB', 'Category': 'Category', 'Installation': 'Installation', 'Features': 'Features', 'Title': 'Title', 'Recommended Software': 'Recommended Software', 'UniCONNECT+': 'UniCONNECT+', 'Make': u'AUDI', 'Price': 'Price', 'Stock Power': 'Stock Power', 'Desctiption': 'Description', 'Related Hardware': 'Related Hardware', 'Year': u'2018', 'Hardware Included': 'Hardware Included', 'Model': u'A4', 'Product Type': 'Product Type', 'LB-FT': 'LB-FT', 'HP': 'HP', 'Octane': 'Octane', 'Media1': 'Media1'}

我已经从循环中调用了函数,并且函数返回具有不同数据的相同字典,我必须将其写入循环中的 CSV 和 Excel 文件 文件应如下所示

Engine | Category | Installation |........ 2.0 TSI MLB | car | 5 |........ 2.0 TSTI MLB | bike | 6 |........ 8.0 BL | car | 8 |........ 2.0 TSI MLB | car | 6 |........

【问题讨论】:

  • 您需要什么样的帮助?请分享您的代码,向我们展示您迄今为止所做的尝试,并提出有效的问题以寻求帮助。

标签: python excel csv dictionary


【解决方案1】:

给你:

import pandas
import os
from openpyxl import load_workbook
import xlsxwriter

sample_dict = {'Engine': u'2.0 TSI MLB', 'Category': 'Category', 'Installation': 'Installation', 'Features': 'Features', 'Title': 'Title', 'Recommended Software': 'Recommended Software', 'UniCONNECT+': 'UniCONNECT+', 'Make': u'AUDI', 'Price': 'Price', 'Stock Power': 'Stock Power', 'Desctiption': 'Description', 'Related Hardware': 'Related Hardware', 'Year': u'2018', 'Hardware Included': 'Hardware Included', 'Model': u'A4', 'Product Type': 'Product Type', 'LB-FT': 'LB-FT', 'HP': 'HP', 'Octane': 'Octane', 'Media1': 'Media1'}

if __name__ == '__main__':
    get_next_dict = iter([sample_dict]*5)
    headers = sample_dict.keys()

    # create csv file if it does not exist
    if not os.path.isfile('test.csv'):
        with open('test.csv', 'w')as csv_file:
            csv_file.writelines(', '.join(headers))

    # create excel file if it does not exist
    if not os.path.isfile('test.xlsx'):
        book = xlsxwriter.Workbook('test.xlsx')
        sheet = book.add_worksheet("TestSheet")
        for (idx, header) in enumerate(headers):
            sheet.write(0, idx, header)
        book.close()

    # open the files and start the loop
    with open('test.csv', 'a+') as csv_file:
        book = load_workbook('test.xlsx')
        sheet = book.get_sheet_by_name('TestSheet')

        # loop through all dictionaries
        for d in get_next_dict:
            values = [d[key] for key in headers]
            csv_string = '\n'+', '.join(values)
            # write to csv file
            csv_file.write(csv_string)
            # write to excel file
            sheet.append(values)
        book.save(filename='test.xlsx')

【讨论】:

    【解决方案2】:

    你写一个新的 csv/excel 吗?还是追加到现有的 csv/excel?

    原则上你可以用pandas做你想做的事。从您的第一个字典创建一个pandas.DataFrame。附加您在循环中获得的所有字典。最后将数据框写入csv或excel:

    # ... bevore the loop
    d = function_that_returns_a_dict()
    df = pandas.DataFrame(d, index=[0])
    # or alternatively read the exising csv/excel and the append all dictionaries
    # df = pandas.read_csv(...)
    # df = pandas.read_excel(...)
    
    #... inside the loop
    d = function_that_returns_a_dict()
    df = df.append(d, ignore_index=True)
    
    # ... after the loop
    df.write_csv('name.csv')
    df.write_excel('name.xlsx')
    

    【讨论】:

    • 我想这样写打开现有的文件,如果不存在则创建它,然后放置标题,然后在循环完成所有循环后将dict附加到文件中
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多