Reputation: 11
I am trying to export an output file as a CSV file.
I have 15 columns and 400 rows.
In my code, I stored data in the dictionary file, which means that I have one dictionary for each column.
So I want to get a CSV file which includes all dictionary in the same file.
I tried to use a (for) loop in order to do that, but it did not work.
Upvotes: 0
Views: 3971
Reputation: 1649
Please Check the variable as per your need. This should work.
def WriteCsv(csvFileName, csvFieldNames, row=None ):
import csv
import os
if row:
if os.path.exists(csvFileName):
f_handle = open(csvFileName, 'a')
csvWriter = csv.DictWriter(f_handle, fieldnames=csvFieldNames)
else:
f_handle = open(csvFileName, 'w+')
csvWriter = csv.DictWriter(f_handle, fieldnames=csvFieldNames)
csvWriter.writeheader()
try:
csvWriter.writerow(row)
finally:
f_handle.close()
for row in dict_data:
WriteCsv(csvFileName="Names.csv",csvFieldNames=csv_columns,row=row)
Upvotes: 0
Reputation: 86
let us Assume your dictionary is like this:
my_dict = {'key1': '1', 'key2': 'b', 'key3': '123'}
To tackle your problem use :
import pandas as pd
(pd.DataFrame.from_dict(data=mydict, orient='columns')
.to_csv('file_name.csv', header=False))
See Ivan Calderon's Answer for more information.!!
Upvotes: 1