2017-09-24 62 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

我想寫這樣打開文件現有的,如果沒有那裏創建它,然後把標題,然後追加字典到循環完成所有循環後不是 –

相關問題