-2
import csv
from itertools import izip
    if l > 0:
            for i in range(0,l):
        combined.append(str(questionList[i]).encode('utf-8') + str(viewList[i]).encode('utf-8'))
#       viewcsv.append(str(viewList[i]).encode('utf-8'))
#       quescsv.append(str(questionList[i]).encode('utf-8'))
        with open('collect.csv', 'a') as csvfile:
             spamwriter = csv.writer(csvfile, delimiter='\n')
             spamwriter.writerow(combined)
#            spamwriter.writerows(izip(quescsv, viewcsv))
        return 1
    else:
        return 0

I need to generate a csv file and flood it with data from 2 or more lists into separate columns and not a single column. Currently I'm trying to combine two lists in one list(combined) and use this as input for writing, but I haven't got desired o/p. I have tried many things including the fieldnames way,izip way, but in vain. Eg: questionList viewList 4 3 views 5 0 views

The numbers used are just for example.

Rohit Raj
  • 1
  • 1
  • 2

2 Answers2

0

Probably, you need something like this:

import csv

X = [1, 2, 3, 4, 5]
Y = [2, 3, 5, 7, 11]
Z = ['two', 'three', 'five', 'seven', 'eleven']

with open('collect.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')
    for row in zip(X, Y, Z):
        writer.writerow(row)
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95
  • the solution is not satisfying the requirement. it is writing in the same column, My query is to write in separate columns. – Rohit Raj Apr 07 '15 at 05:52
0
import csv

X = [1, 2, 3, 4, 5]
Y = [2, 3, 5, 7, 11]
Z = ['two', 'three', 'five', 'seven', 'eleven']

with open('collect.csv', 'w') as csvfile:
    writer = csv.writer(csvfile, delimiter=',')

    writer.writerow(X)
    writer.writerow(Y)
    writer.writerow(Z)
Fomalhaut
  • 8,590
  • 8
  • 51
  • 95