niub
niub

Reputation: 19

Writing into a .csv file

I have an array and some code that gets rid of duplicate names, along with their previous three values.

file = ['Sorin,0,0,0', 'Sorin,0,1,0', 'David,0,0,0', 'Sorin,0,0,0', 'Sorin,0,0,0']
['Sorin', '0', '0', '0']
import json
Dict = {}

for line in file:
  line = line.split(",")
  key, value = line[0], line[1:]
  Dict[key] = value

Zip = list(zip(Dict.keys(), Dict.values()))

with open("Class1.csv","w",newline="") as f:
    writer = csv.writer(f)
    writer.writerows(Zip)

I am trying to write the array back into the .csv file but I am getting an issue. I am quite new to writing in .csv so I'm sorry.

print(Zip)
#Output
[('Sorin', ['0', '0', '0']), ('David', ['0', '0', '0'])]

The issue is when I try to write it into the .csv file. It writes the values in the columns incorrectlyas:

......A..............B

1...Sorin..[0,0,0]

2...David..[0,0,0]

I want it to be written as:

..........A........B...C...D

1...Sorin.....0...0...0

2...David....0...0...0

Upvotes: 0

Views: 69

Answers (1)

Sachin Kohli
Sachin Kohli

Reputation: 1986

I think... the issue is in list "Zip"... Try this code, where in Zip list, each both keys & values from dict will be individual list...

file = ['Sorin,0,0,0', 'Sorin,0,1,0', 'David,0,0,0', 'Sorin,0,0,0', 'Sorin,0,0,0']

import csv
Dict = {}

for line in file:
  line = line.split(",")
  key, value = line[0], line[1:]
  Dict[key] = value

Zip = [["A","B","C","D"]] # Create empty list as Zip = [] if you don't want A,B,C,D as columns
for k,v in Dict.items():
    Zip.append([k]+v)

with open("Class1.csv","w",newline="") as f:
    writer = csv.writer(f)
    writer.writerows(Zip)

enter image description here

Upvotes: 2

Related Questions