如何将dict添加到python中的csv文件和excel文件中

我有Python的字典,我想追加到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 |........

干得好:

 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') 

你写一个新的csv / excel? 或者你追加到现有的CSV / Excel?

原则上你可以用pandas做你想做的。 从你的第一个字典创build一个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')