Home > Blockchain >  write a CSV file by column in Python
write a CSV file by column in Python

Time:07-10

I have this code and I need to writing by column, by example I need the output be like this:

columnA  columnB  columnC  columnD
Hello,1  World,2  Monty,3  Python,4

Not like this:

Hello,1
World,2
Monty,3
Python,4

Code:

list_1 = ["Hello", "World", "Monty", "Python"]
list_2 = [1, 2, 3, 4]
file = open("columns.txt", "w")
writer = csv.writer(file)
for w in range(4):
iterate through integers 0-3
writer.writerow([list_1[w], list_2[w]])
file.close()

CodePudding user response:

You can use the lineterminator option to redifine what csv.writer writes after each row. It doesn't have to be a newline - spaces work just as well. Using a couple of other features (zip to iterate the lists and writerows to get rid of the for loop), you could do

import csv

list_1 = ["Hello", "World", "Monty", "Python"]
list_2 = [1, 2, 3, 4]
with open("columns.txt", "w", newline="") as file:
    writer = csv.writer(file, lineterminator="  ")
    writer.writerows(zip(list_1, list_2))
  • Related