y3trgfhsfgr
y3trgfhsfgr

Reputation: 467

exporting data into a column of an excel file in python

here is my code:

import random
from random import shuffle

fileName = 'test'
dataFile = open("DD" + fileName+'.csv', 'w')
dataFile.write('trial,numbers') #data headers for .csv file

a = [1,2]

for i in range(4):
     shuffle(a)
     if a == [1,2]:
         num = 'top'
     else:
         num = 'bottom'

    print a
    print num

    info = []
    i = str(i)
    info.append(',')
    info.append(i)
    info.append(',')
    info.append(num)

    dataFile.writelines(info)

This code randomizes an order then labels it either 'top' or 'bottom' 4 times, and exports the a excel file. The problem is that when it exports it puts it in a row. What I would like to do is have it exported into a column so that they are under the headlines 'trial' and 'numbers'. Any help would be greatly appreciated. :)

Upvotes: 0

Views: 56

Answers (1)

Burhan Khalid
Burhan Khalid

Reputation: 174614

You are not writing any end-of-line characters, so everything will be in one line (which is why you are seeing it all as a row).

Using the csv module, you can simplify your code:

import csv
import random

a = [1,2]

with open('DD{}filename.csv'.format(fileName), 'w') as f:
    writer = csv.writer(f, delimiter=',')
    writer.writerow(['trial','numbers']) # Note this is a two element
                                         # list, not a string

    for i in range(4):
        random.shuffle(a)
        if a == [1,2]:
           num = 'top'
        else:
           num = 'bottom'

        writer.writerow([i, num])

Upvotes: 1

Related Questions