2

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!

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot, using the row.values() solved my problem
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.