2017-09-24 71 views
0

我有python中的字典,我想将它附加到CSV文件和Excel文件中。如何将dict添加到csv文件和python中的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 |........

+1

你要问什么样的帮助呢?请分享你的代码,告诉我们你到目前为止已经尝试了什么,并询问有效的问题以寻求帮助。 –

回答

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

谢谢,它工作绝对很棒@piiipmatz –

0

你写一个新的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') 
+0

我想写这样打开文件现有的,如果没有那里创建它,然后把标题,然后追加字典到循环完成所有循环后不是 –

相关问题