Output format of python code in csv file

I have the following python code. It is supposed to print the output in table type format into a csv file e.g.

A  B  C  D  E  F  G  H  I  J
2  4  5  7  9  7  6  5  4  2
.
.
.

But the output is printing one value per line

A
B
C
.
.
.
2
3
4
.
.

Here is the code

import random
import csv

with open('table.csv', 'w') as file:
    csv_write = csv.writer(file,delimiter='\t')


    for i in range(ord('A'), ord('J')+1):
        row = [chr(i)]
        csv_write.writerow(row)

    for j in range(1,11):
        for k in range(1,1001):
            row2 = [random.randint(1,10001)]
            csv_write.writerow(row2)

2 answers

  • answered 2018-04-17 06:14 Rao Sahab

    import random
    import csv
    
    with open('table.csv', 'w', newline='') as file:
        csv_write = csv.writer(file,delimiter='\t')
        header = [ chr(i) for i in range(ord('A'), ord('J')+1)]
        csv_write.writerow(header)
    
        for k in range(1,1001):
            row = random.sample(range(1,10001), 10)
            csv_write.writerow(row)
    

  • answered 2018-04-17 06:51 Om Prakash

    Make list outer loop.`

    import random
    import csv
    
    with open('table.csv', 'w') as file:
        csv_write = csv.writer(file, delimiter=',')
        col = []
        row2 = []
    
        for i in range(ord('A'), ord('J')+1):
            col.append(chr(i))
        csv_write.writerow(col)
    
        for j in range(1):
            for k in range(1,11):
                row2.append(random.randint(1,10))            
        csv_write.writerow(row2)
    

    `