-1

I am trying to put a list of dictionaries in a csv format using the package csv. I am able to convert the list of dictionary in a csv file but I need the content to be written in a variable. Here is the code :

keys = dict_all_data[0].keys()
with open('all_data.csv', 'w')  as output_file:
        dict_writer = csv.DictWriter(output_file, keys, extrasaction='ignore')
        dict_writer.writeheader()
        dict_writer.writerows(dict_all_data)

In pandas, there is a simple way to put the csv content in a variable by not precising the name of the csv to write.

result = df_result.to_csv(index=False)

Is there a way to do this similarly with the package csv, please ?

Best regards.

C. Boyer
  • 97
  • 9

1 Answers1

1

You can save the generated csv to sring buffer (io.StringIO):

import csv
from io import StringIO

# where to save the csv (string buffer)
s = StringIO()

# some data:
dict_all_data = [{'column_1':1, 'column_2':2}, {'column_1':3, 'column_2':4}]

# save the csv to string buffer:
keys = dict_all_data[0].keys()
dict_writer = csv.DictWriter(s, keys, extrasaction='ignore')
dict_writer.writeheader()
dict_writer.writerows(dict_all_data)

# print content of the buffer:
s.seek(0)
print(s.read())

Prints:

column_1,column_2
1,2
3,4
Andrej Kesely
  • 168,389
  • 15
  • 48
  • 91
  • 1
    I did not mention that I work using Python 2.7. I tried your code using io.BytesIO and it works, thank you. – C. Boyer Oct 22 '20 at 15:44