Home > Back-end >  csv.DictWriter writeheader() and writerow do not write properly Greek characters in CSV file when di
csv.DictWriter writeheader() and writerow do not write properly Greek characters in CSV file when di

Time:01-10

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:

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()

CodePudding user response:

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.

  •  Tags:  
  • Related