Home > Software design >  How do i convert 3D list in python to csv file?
How do i convert 3D list in python to csv file?

Time:04-19

I have a 3D list like

final_arr = [[[1,2,3,4],2],[[1,1,2,2],3],[[1,2,2],4]]

Now I want to convert each row into csv column, like for first list item the columns should be 1 2 3 4 2 in csv single row and multiple columns.

Right now I am doing this but the whole list is becoming single column in csv:

import csv

with open("out1.csv", "w", newline="") as f:
    writer = csv.writer(f)
    writer.writerows(final_arr)

CodePudding user response:

As an extension of Aivar's answer,

Your list is not a 3D list. It is a 2D list where elements can be an array. For the provided array, we can apply this Alvar's answer. You may want to add a separator while printing inside the file.

final_arr = [[[1,2,3,4],2],[[1,1,2,2],3],[[1,2,2],4]]

with open('out1.csv', 'w') as f:
    for (i, j) in final_arr:
        print(*i, j, file=f, sep=',')

CodePudding user response:

Is objective something like this:

final_arr = [[[1,2,3,4],2],[[1,1,2,2],3],[[1,2,2],4]]


with open('out1.csv', 'w') as f:
    for (i, j) in final_arr:
        print(*i, j, file=f)

# out1.csv
1 2 3 4 2
1 1 2 2 3
1 2 2 4

EDIT: as suggested by @juanpa.arrivillaga same approach with using csv module and writerow:

import csv

with open('out1.csv', 'w', newline="") as f:
    writer = csv.writer(f, delimiter=" ")
    for (i, j) in final_arr:
        writer.writerow((*i, j))

and with writerows:

with open('out1.csv', 'w', newline="") as f:
    writer = csv.writer(f, delimiter=" ")
    writer.writerows((*i, j) for (i, j) in final_arr)

  • Related