from random import random
import profile

def cellwrite(filename, cellarray):
    rows, cols = len(cellarray), len(cellarray[0])
    fid = file(filename, 'w')
    for i_row in range(rows):
        cells = []
        for i_col in range(cols):
            contents = cellarray[i_row][i_col]
            if isinstance(contents, (int, float, long)):
                contents = str(contents)
            cells.append(contents)
        file_line = ','.join(cells)
        file_line = ''.join([file_line, '\n'])
        fid.write(file_line)
    fid.close()
    
def cellwrite2(filename, cellarray):
    fid = file(filename, 'w')
    lines = [','.join(map(str, row))+'\n' for row in cellarray]
    fid.writelines(lines)
    fid.close()

def cellwrite3(filename, cellarray):
    fid = file(filename, 'w')
    lines = [','.join([str(cell) for cell in row])+'\n' for row in cellarray]
    fid.writelines(lines)
    fid.close()

if __name__=='__main__':
    C = [[random() for col in range(100)] for row in range(1000)]
    profile.run("cellwrite('a.csv', C)")
    profile.run("cellwrite2('b.csv', C)")
    profile.run("cellwrite3('c.csv', C)")
