我在python中有dict,我想将它附加到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 |........
我从循环中调用了函数,函数返回不同数据的相同dict,我必须将它写入循环中的CSV和Excel文件 文件应如下所示
{{1}}
答案 0 :(得分: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')
答案 1 :(得分: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')