Search code examples
pythonfilerowvertical-text

Python : I get vertical text when I use writerows(zip())


I am trying to write a Python script to create a file of multiple rows with a title and the values stored in columns. I am very new to Python so there might be a stupid mistake somewhere but I have tried many things, looked on the Internet but I cannot find how to solve my isssue...

import csv
A=[1,2]
B=[1.5,0.5]
C=[2.5,3]
with open('test.txt', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f, delimiter='\t')
    writer.writerows(zip("TestA","TestB","TestC"))
    writer.writerows(zip(A,B,C))

I am expecting something like :

TestA     TestB     TestC
1    1.5    2.5
2    0.5    3

But I get :

T     T     T
e     e     e
s     s     s
t     t     t
A     B     C
1     1.5   2.5
2     0.5   3

Does anyone have a idea to get what I want please ? Thank you !


Solution

  • There is no way to write horizontally using writer.writerows() without having to do some complex list transposing. Instead why not use File write() like so:

    A=[1,2]
    B=[1.5,0.5]
    C=[2.5,3]
    with open('test.txt', 'w', newline='', encoding='utf-8') as f:
        f.write('TestA\tTestB\tTestC\n')
        for i in range(2):
            f.write(str(A[i]) + "\t")
            f.write(str(B[i]) + "\t")
            f.write(str(C[i]) + "\t\n")
    

    which produces:

    TestA   TestB   TestC
    1   1.5 2.5 
    2   0.5 3   
    
    

    Here's another link that should be helpful: Correct way to write line to file?