I have list of dict with UTF-8
and I want to save it in txt
file
ls_dict = [
{ 'a': 'میلاد'},
{ 'b': 'علی'},
{ 'c': 'رضا'}
]
I want it to save in csv
or txt
with UTF-8
CodePudding user response:
You just need to make sure you specify the relevant encoding when you create/open the output file.
import json
ls_dict = [
{ 'a': 'میلاد'},
{ 'b': 'علی'},
{ 'c': 'رضا'}
]
with open('j.json', 'w', encoding='utf-8') as j:
j.write(json.dumps(ls_dict))
Subsequently...
with open('j.json', encoding='utf-8') as j:
j = json.load(j)
print(j)
Output:
[{'a': 'میلاد'}, {'b': 'علی'}, {'c': 'رضا'}]
CodePudding user response:
you can save it as a csv
using pandas
ls_dict = [
{ 'a': 'میلاد'},
{ 'b': 'علی'},
{ 'c': 'رضا'}
]
# you could flatten the list of dicts into a proper DataFrame
result = {}
for k in ls_dict:
result.update(k)
# output from above {'a': 'میلاد', 'b': 'علی', 'c': 'رضا'}
# create DataFrame
df = pd.DataFrame(result)
# a b c
# 0 میلاد علی رضا
# the default encoding for Pandas is utf-8
# https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html
df.to_csv('filename.csv')