[英]Append dictionary into EXCEL file by python
This is my function, by using this i am trying to create(if file not exist) or append the dictionary into file.
这是我的 function,通过使用这个我试图创建(如果文件不存在)或 append 字典到文件中。
headers = dict.keys()
if not os.path.isfile('metrics1.csv'):
with open('metrics1.csv', 'w')as csv_file:
csv_file.writelines(', '.join(headers))
if not os.path.isfile('metrics1.xlsx'):
book = xlsxwriter.Workbook('metrics1.xlsx')
sheet = book.add_worksheet("TestSheet")
for (idx, header) in enumerate(headers):
sheet.write(0, idx, header)
book.close()
with open('metrics1.csv', 'a+') as csv_file:
book = load_workbook('metrics1.xlsx')
sheet = book.get_sheet_by_name('TestSheet')
for d in dict:
values = [d[key] for key in headers]
csv_string = '\n'+', '.join(values)
csv_file.write(csv_string)
sheet.append(values)
book.save(filename='metrics1.xlsx')
i got following error,
我收到以下错误,
values = [d[key] for key in headers]
TypeError: string indices must be integers
You need to fix several things.你需要修复几件事。 First and foremost, do not name any variables
dict
.首先,不要命名任何变量
dict
。 dict
is a python built-in keyword. dict
是 python 内置关键字。 We'll assume that you've renamed it data
in the code below.我们假设您已在下面的代码中将其重命名为
data
。
Second, you can create your headers list a little more easily:其次,您可以更轻松地创建标题列表:
headers = list(data.keys()) # or [ key for key in data ]
Third, and finally, is the line where you want to extract value from a dictionary:第三,也是最后,是您要从字典中提取值的行:
values = [data[key] for key in headers]
Hope this helps!希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.