Swish41
Swish41

Reputation: 11

csv.writer returning strange results

my code looks like this:

import csv

mesta=["Ljubljana","Kranj","Skofja Loka","Trzin"]
opis=["ti","mene","ti mene","ne ti mene"]
delodajalci=["GENI","MOJEDELO","MOJADELNICA","HSE"]
ime=["domen","maja","andraz","sanja"]
datum=["2.1.2014","5.10.2014","11.12.2014","5.5.2014"]

with open('sth.csv','w',newline='') as csvfile:
    zapis = csv.writer(csvfile, delimiter=' ')
    dolzina=len(datum)
    i=0
    while i<dolzina:
        zapis.writerows([ime[i]+","+delodajalci[i]+","+opis[i]+","+datum[i]+","+mesta[i]])
        i+=1

and for some strange reason my result looks like: d o m e n G E N I t i 2 . 1 . 2 0 1 4 L j u b l j a n a m a j a M O J E D E L O m e n e 5 . 1 0 . 2 0 1 4 K r a n j a n d r a z M O J A D E L N I C A t i " " m e n e 1 1 . 1 2 . 2 0 1 4 S k o f j a " " L o k a s a n j a H S E n e " " t i " " m e n e 5 . 5 . 2 0 1 4 T r z i n

So a 4 rows x 5 column table.

I would like advice on how to make these white spaces and " " go away. So that for instance d o m e n would be domen and S k o f j a " " L o k a, Skofja Loka. I would be forever grateful for your help. Oh and if it is possibile to do it without any other modules that'd be even better since I have a problem installing them on this computer aswell :(

Thank you for your time.

Upvotes: 0

Views: 68

Answers (1)

Joel
Joel

Reputation: 23887

import csv

mesta=["Ljubljana","Kranj","Skofja Loka","Trzin"]
opis=["ti","mene","ti mene","ne ti mene"]
delodajalci=["GENI","MOJEDELO","MOJADELNICA","HSE"]
ime=["domen","maja","andraz","sanja"]
datum=["2.1.2014","5.10.2014","11.12.2014","5.5.2014"]

with open('sth.csv','w') as csvfile:
    zapis = csv.writer(csvfile)
    zapis.writerows(zip(ime,delodajalci,opis,datum,mesta))

creates the output:

domen,GENI,ti,2.1.2014,Ljubljana

maja,MOJEDELO,mene,5.10.2014,Kranj

andraz,MOJADELNICA,ti mene,11.12.2014,Skofja Loka

sanja,HSE,ne ti mene,5.5.2014,Trzin

In what you had, writerows was getting a single string (including commas between what you wanted). You wanted it to just print that string out. But the csvwriter wants to print a list with a separator between entries. It only had a string, so when it treats that as a list, each character gets printed, then the separator.

In what I've done, I've got writerows receiving a bunch of lists. Each list comes from zip, so each list consists of the 'i'th entries of the arguments zip got.

edit removed dolzina and i=0 since not needed anymore.

Upvotes: 1

Related Questions