2017-09-24 1 views
0

나는 파이썬에서 dict을 가지고 있는데 CSV 파일과 엑셀 파일에 덧붙이고 싶다.dict를 csv 파일에 추가하고 파이썬에서 파일을 엑셀로 변환하는 방법

나는 아래의 DICT

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 쓰기 마십시오 아래 같아야/엑셀? 또는 기존 csv/excel에 추가합니까?

원칙적으로 pandas으로 원하는 것을 할 수 있습니다. 첫 번째 딕트에서 pandas.DataFrame을 만듭니다. 루프 내부에있는 모든 사전을 추가하십시오. 결국를 CSV로 데이터 프레임을 작성하거나 엑셀 : 여기

# ... 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

나는이 파일을 기존처럼 열어서 쓰고 싶다면 거기에 파일을 만들고 헤더를 넣은 다음 루프에 모든 루프가 완료된 후 파일을 추가하지 말라. –

관련 문제