Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

csv.DictWriter writeheader() and writerow do not write properly Greek characters in CSV file

Using python v3.7.8, I’m trying to read data from JSON file and write some data in CSV. JSON contains Greek and Latin Characters.

Data from JSON are read properly (I print them). However, when I’m writing data to CSV, Greek characters and not shown properly.

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import json
import csv

# Opening JSON file to read data
f = open('test_2021-11-22-Andrias_lecture.json', 'r',encoding= 'utf-8')
# returns JSON object as a dictionary
data = json.load(f)

namesRowList=[]
namesColumnList=[]
connectionCountList=[]
connectionCountListTemp=[]
connectionsRow = {'':''}

# Iterating through the json list
for i in data['playerArray']:
    namesRowList.append(i['score'])
    namesColumnList.append(i['score'])
    connectionsRowTemp = {i['score']:''}
    connectionsRow.update(connectionsRowTemp)
    
print(connectionsRow)
        
# Open CSV file to store data
with open('matrix_10_Jan_2022.csv', 'w', newline='', encoding='utf-8') as file:
    headerList = [''] + namesRowList.copy()
    
    dw = csv.DictWriter(file, delimiter=';', fieldnames=headerList)
    dw.writeheader()
    
    
    for i in data['playerArray']:
        name = i['score']
        connections = i['connections']
        connectionsRow['']=name
        index = 0
        
        for name in namesRowList:
            for con in connections:
                if (name == con):
                    connectionsRow[name] = 1
                else:
                    connectionsRow[name] = 0
            index = index + 1

        dw.writerow(connectionsRow)
   file.close()

>Solution :

Excel requires the byte order mark (BOM) signature or it will interpret the file in the local ANSI encoding. There is a codec for that, utf-8-sig.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading