writing data from a python list to csv row-wise
Question:
Using python, i am writing data from a list to a .csv file, row-wise.
Code:
writer=csv.writer(open(filepath,'wb'))
header=['type','id','numberOfUpdates','isPingEnabled','lastUpdated']
length_list=len(header)
i=0
while i!=length_list :
data=header[i]
print data
i=i+1
writer.writerow(data)
Result: Data is being written to csv file but each letter is printed in each column.
For example: type is written as ‘t’ in one column, ‘y’ in next column and so on.
I need the whole word in one column. Can some one point out what change can i make?
Thanks
Answers:
Change writer.writerow(data)
to writer.writerow([data])
.
.writerow
takes an iterable and uses each element of that iterable for each column. If you use a list with only one element it will be placed in a single column.
You should also restructure your loop:
for word in header:
writer.writerow([word])
This work for me:
for item in RESULTS:
wr.writerow([item,])
Using python, i am writing data from a list to a .csv file, row-wise.
Code:
writer=csv.writer(open(filepath,'wb'))
header=['type','id','numberOfUpdates','isPingEnabled','lastUpdated']
length_list=len(header)
i=0
while i!=length_list :
data=header[i]
print data
i=i+1
writer.writerow(data)
Result: Data is being written to csv file but each letter is printed in each column.
For example: type is written as ‘t’ in one column, ‘y’ in next column and so on.
I need the whole word in one column. Can some one point out what change can i make?
Thanks
Change writer.writerow(data)
to writer.writerow([data])
.
.writerow
takes an iterable and uses each element of that iterable for each column. If you use a list with only one element it will be placed in a single column.
You should also restructure your loop:
for word in header:
writer.writerow([word])
This work for me:
for item in RESULTS:
wr.writerow([item,])