Mike
Mike

Reputation: 23

Storing list in to csv file using python

I'm trying to store a type list variable in to a csv file using python. Here is what I got after hours on StackOverflow and python documentation:

Code:

row = {'SgDescription': 'some group', 'SgName': 'sku', 'SgGroupId': u'sg-abcdefgh'}
new_csv_file = open("new_file.csv",'wb')
ruleswriter = csv.writer(new_csv_file,dialect='excel',delimiter=',')
ruleswriter.writerows(row)
new_csv_file.close()

Result:

$ more new_file.csv 
S,g,D,e,s,c,r,i,p,t,i,o,n
S,g,N,a,m,e
S,g,G,r,o,u,p,I,d

Can anyone please advice how to store the values to the file like this:

some group,sku,sg-abcdefgh

Thanks a ton!

Upvotes: 2

Views: 3505

Answers (2)

SparkAndShine
SparkAndShine

Reputation: 18027

Extract your desired data before writing into a csv file,

row = [row['SgDescription'], row['SgName'], row['SgGroupId']]       # ['some group', 'sku', u'sg-abcdefgh']


# write to a csv file
with open("new_file.csv",'wb') as f:
    ruleswriter = csv.writer(f)
    ruleswriter.writerow(row)

PS: if you don't care about the order, just use row.values().


Or use csv.DictWriter,

import csv

row = {'SgDescription': 'some group', 'SgName': 'sku', 'SgGroupId': u'sg-abcdefgh'}
with open('new_file.csv', 'w') as csvfile:
    fieldnames = ['SgDescription', 'SgName', 'SgGroupId']
    writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    writer.writerow(row)

Upvotes: 1

izak
izak

Reputation: 583

writerows() expects a sequence of sequences, for example a list of lists. You're passing in a dict, and a dict happens to be iterable: It returns the keys of the dictionary. Each key -- a string -- happens to be iterable as well. So what you get is an element of each iterable per cell, which is a character. You got exactly what you asked for :-)

What you want to do is write one row, with the keys in it, and then maybe another with the values, eg:

import csv

row = {
    'SgDescription': 'some group',
    'SgName': 'sku',
    'SgGroupId': u'sg-abcdefgh'
}


with open("new_file.csv",'wb') as f:
    ruleswriter = csv.writer(f)
    ruleswriter.writerows([row.keys(), row.values()])

If order is important, use collections.OrderedDict.

Upvotes: 1

Related Questions